4 回答

TA贡献2021条经验 获得超8个赞
在一行中:
string s = "apple";
s = $"{s.Substring(0, s.Length - 2)}{s[s.Length - 1]} {s[s.Length - 2]}";

TA贡献1770条经验 获得超3个赞
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贡献1810条经验 获得超5个赞
在 C#string中,类型是不可变的,这意味着您不能修改已创建的字符串。如果您需要完成多项修改,通常的方法是使用StringBuilder类
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贡献1812条经验 获得超5个赞
您可以使用方法将您的string转换为。在此交换后最后 2 个字符,然后在它们之间添加空格,就像这样: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 关注
- 142 浏览
添加回答
举报