如何更改字符串中最后两个字符的位置,并在c#中添加空格?
例如,我有一个简单的字符串“ apple”,需要将其更改为“ appe l”。
我尝试了几件事,但没有成功。
提前感谢所有答案。
答案 0 :(得分:1)
一行:
string s = "apple";
s = $"{s.Substring(0, s.Length - 2)}{s[s.Length - 1]} {s[s.Length - 2]}";
答案 1 :(得分:1)
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();
答案 2 :(得分:0)
在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, ' ');
答案 3 :(得分:0)
您可以使用string
方法将char Array
转换为string.ToCharArray()
。交换之后,最后2个字符,然后在它们之间添加空格,如下所示:
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);
}