例如,我有两个字符串变量:
string a = " Hello ";
string b = " World ";
如何在没有临时变量的情况下交换它?
我找到了一个例子,但它使用第三个变量作为a
的长度:
int len1 = a.Length;
a = a + b;
b = a.Substring(0, len1);
a = a.Substring(len1);
我该怎么做?
答案 0 :(得分:3)
您可以在不使用临时变量的情况下使用SubString
,如下所示:
string a = " Hello ";
string b = " World ";
a = a + b;//" Hello World "
b = a.Substring(0, (a.Length - b.Length));//" Hello "
a = a.Substring(b.Length);//" World "
答案 1 :(得分:0)
只需使用其他一些交换手段。
string stringOne = "one";
string stringTwo = "two";
stringOne = stringOne + stringTwo;
stringTwo = stringOne.Substring(0, (stringOne.Length - stringTwo.Length));
stringOne = stringOne.Substring(stringTwo.Length);
// Prints stringOne: two stringTwo: one
Console.WriteLine("stringOne: {0} stringTwo: {1}", stringOne, stringTwo);
答案 2 :(得分:0)
string str1 = "First";
string str2 = "Second";
str1 = (str2 = str1 + str2).Substring(str1.Length);
str2 = str2.Substring(0,str1.Length-1);