4 回答

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
在一行中:
string s = "apple";
s = $"{s.Substring(0, s.Length - 2)}{s[s.Length - 1]} {s[s.Length - 2]}";

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
string s = "apple";
var sb = new StringBuilder(s);
var temp = sb[sb.Length - 2];
sb[sb.Length - 2] = sb[sb.Length - 1];
sb[sb.Length - 1] = temp;
sb.Insert(s.Length - 1, " ");
s = sb.ToString();

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
在 C#string中,類(lèi)型是不可變的,這意味著您不能修改已創(chuàng)建的字符串。如果您需要完成多項(xiàng)修改,通常的方法是使用StringBuilder類(lèi)
string s = "apple";
var buf = new StringBuilder(s);
var ch = buf[buf.Length - 1];
buf[buf.Length - 1] = buf[buf.Length - 2];
buf[buf.Length - 2] = ch;
buf.Insert(s.Length - 1, ' ');

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用方法將您的string轉(zhuǎn)換為。在此交換后最后 2 個(gè)字符,然后在它們之間添加空格,就像這樣:char Arraystring.ToCharArray()
static void Main(string[] args)
{
string fruit = "apple";
char[] charFruit = fruit.ToCharArray();
char temp = charFruit[charFruit.Length - 1]; // holds the last character of the string
charFruit[charFruit.Length - 1] = charFruit[charFruit.Length - 2]; //interchnages the last two characters
charFruit[charFruit.Length - 2] = temp;
fruit = "";
for (int i = 0; i < charFruit.Length; i++){
if (i == charFruit.Length - 2){
fruit += charFruit[i].ToString();
fruit += " ";
}
else
fruit += charFruit[i].ToString();
}
Console.WriteLine(fruit);
}
- 4 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報(bào)