C#|在不使用第三个用户定义变量的情况下交换两个字符串

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

null

例子:

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

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

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

  • 一串子串方法(startIndex) :此方法用于从字符串的当前实例检索子字符串。参数“startIndex”将指定子字符串的起始位置,然后子字符串将继续到字符串的末尾。
  • 绳子。子字符串方法(int startIndex,int length) STARTING指定了一个STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING STARTING。如果startIndex等于字符串的长度,并且参数长度为零,那么它将不返回任何内容作为子字符串。

算法:

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 initial 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
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享