为了账号安全,请及时绑定邮箱和手机立即绑定

在c#中更改字符位置并在它们之间添加空格

在c#中更改字符位置并在它们之间添加空格

C#
江户川乱折腾 2022-10-23 16:02:05
您将如何更改字符串中最后两个字符的位置并在 c# 中在它们之间添加空格?例如,我有一个简单的字符串“apple”,需要将其更改为“appe l”。我尝试了几件事,但没有任何成功。提前感谢所有答案。
查看完整描述

4 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

在一行中:


string s = "apple";

s = $"{s.Substring(0, s.Length - 2)}{s[s.Length - 1]} {s[s.Length - 2]}";


查看完整回答
反对 回复 2022-10-23
?
德玛西亚99

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();


查看完整回答
反对 回复 2022-10-23
?
森栏

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, ' ');


查看完整回答
反对 回复 2022-10-23
?
慕雪6442864

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);

}


查看完整回答
反对 回复 2022-10-23
  • 4 回答
  • 0 关注
  • 142 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号