C# string 如果替换指定位置的字符

键盘上的疯兔 2012-12-28 10:41:01
C#中的string中的内容是只读的,但又不像C++一样提供一个replace成员函数,那我怎么可以舒服一点地修改某个位置上的字符呀?
比如:
string s = "hello world!";

我想把第3个位置上的'l'替换成'L',C++中可以这样做:
s.replace(3, 1, 1, 'L');

C#怎么做呢?

还有C#的string 与 ArrayList 连个find方法都没有,也不提供C++中的 set<T>, string是引用类型但赋值时又重新分配内存……

真受不了这玩意, 引用 Bjarne Stroustrup 的一段话:
"It will take a lot to persuade me that the world needs yet another proprietary language. It will be especially hard to persuade me that it needs a language that is closely integrated with a specific proprietary operating system. "
...全文
15118 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2014-10-09
  • 打赏
  • 举报
回复
 string str = " hello word";
            //StringBuilder sb = new StringBuilder(str);
            //sb.Replace("l", "L", 3, 1);
            //str = sb.ToString();

            str = str.Remove(3, 1);
            str = str.Insert(3, "L");
后端Q 2014-10-08
  • 打赏
  • 举报
回复
string s = "hello world!"; ; s = s.Insert(2, "L"); s = s.Remove(2, 1);
Snowdust 2012-12-28
  • 打赏
  • 举报
回复
string s = "hello world!";
char[] ch = s.ToCharArray();
ch[3] = 'L';
s = new string(ch);
showjim 2012-12-28
  • 打赏
  • 举报
回复
或者
            string s = "hello world!";
            fixed (char* sf = s) sf[3] = 'L';
showjim 2012-12-28
  • 打赏
  • 举报
回复
            string s = "hello world!";
            fixed (char* sf = s) *(sf + 3) = 'L';
键盘上的疯兔 2012-12-28
  • 打赏
  • 举报
回复
引用 3 楼 bdmh 的回复:
C# code?123 string s = "hello world!"; ; s = s.Remove(2, 1); s = s.Insert(2, "L");
这个方式比较简洁,但这性能,还是不完美。
键盘上的疯兔 2012-12-28
  • 打赏
  • 举报
回复
引用 2 楼 hjywyj 的回复:
string s = "hello world!"; s = Regex.Replace(s, @"(?<=^(.){2}).", "L"); string s = "hello world!"; s = Regex.Replace(s, @"(?<=^(.*?l){2}.*?)l", "L");
还得搬出正则表达式?
healer_kx 2012-12-28
  • 打赏
  • 举报
回复
一定要深入的了解,C#的string对象是个un-mutable的对象。一旦有了对象,你就不可能change 它。
bdmh 2012-12-28
  • 打赏
  • 举报
回复

            string s = "hello world!"; ;
            s = s.Remove(2, 1);
            s = s.Insert(2, "L");
  • 打赏
  • 举报
回复
string s = "hello world!"; s = Regex.Replace(s, @"(?<=^(.){2}).", "L"); string s = "hello world!"; s = Regex.Replace(s, @"(?<=^(.*?l){2}.*?)l", "L");
lihanbing 2012-12-28
  • 打赏
  • 举报
回复

        string s = "hello world!";
        StringBuilder sb = new StringBuilder(s);
        sb.Replace("l", "L", 3, 1);
        s = sb.ToString();

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧