📌  相关文章
📜  C#|交换两个字符串,而不使用第三个用户定义的变量

📅  最后修改于: 2021-05-29 20:29:06             🧑  作者: Mango

给定两个字符串变量a和b,在不使用C#中的临时变量或第三个变量的情况下交换这些变量。允许使用库方法。

例子:

Input:
a = "Hello"
b = "World"

Output:
Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

这个想法是进行字符串连接,然后使用Substring()方法执行此操作。 Substring()方法有两种形式,如下所示:

  • String.Substring方法(startIndex) :此方法用于从字符串的当前实例检索子字符串。参数“ startIndex”将指定子字符串的开始位置,然后子字符串将继续到字符串的末尾。
  • String.Substring方法(int startIndex,int length) :此方法用于提取从参数startIndex描述的指定位置开始并具有指定长度的子字符串。如果startIndex等于字符串的长度并且参数length为零,则它将不作为子字符串返回任何内容。


算法:

1) Append second string to first string and 
   store in first string:
   a = a + b

2) Call the Substring Method (int startIndex, int length)
   by passing startindex as 0 and length as,
   a.Length - b.Length:
   b = Substring(0, a.Length - b.Length);

3) Call the Substring Method(int startIndex) by passing 
   startindex as b.Length as the argument to store the 
   value of initial b string in a
   a = Substring(b.Length);
// C# program to swap two strings
// without using a temporary variable.
using System;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // Declare two strings
        String a = "Hello";
        String b = "Geeks";
  
        // Print String before swapping
        Console.WriteLine("Strings before swap: a =" + 
                          " " + a + " and b = " + b);
  
        // append 2nd string to 1st
        a = a + b;
  
        // store intial string a in string b
        b = a.Substring(0, a.Length - b.Length);
  
        // store initial string b in string a
        a = a.Substring(b.Length);
  
        // print String after swapping
        Console.WriteLine("Strings after swap: a =" +
                          " " + a + " and b = " + b);
    }
}

输出:

Strings before swap: a = Hello and b = Geeks
Strings after swap: a = Geeks and b = Hello