如何改变字符串的第n个元素 [英] how to change nth element of the string

查看:109
本文介绍了如何改变字符串的第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好结果
I在C#代码像下面

 字符串s =新的字符串( 〜,25); 
INT IND = 5;
S [IND] ='A';



它给出了一个错误结果
属性或索引string.this [INT]'不能被分配到 - 它是只读结果
这样有什么问题,
和如何解决它。


<。 DIV CLASS =h2_lin>解决方案

字符串是不可变的 - 你不能改变现有的



两种选择:




  • 使用的StringBuilder ,如:

      StringBuilder的建设者=新的StringBuilder(新建字符串('〜',25)); 
    建设者[5] ='A';
    字符串结果= builder.ToString();


  • 建立从字符数组一个新的字符串:

     的char [] =字符新的字符串('〜',25).ToCharArray(); 
    字符[5] ='A';
    字符串结果=新的字符串(字符);




在这两种情况下,你可以填充可变数据没有建立一个新的字符串开始,如果你想 - 这将涉及更多的代码,但很可能是更有效的。



另外,你可以把串并连接在一起,按照另一种答案......基本上有很多的解决这一途径。哪一个是合适的,将取决于您的实际使用案例。


Hi everybody
i have a code in c# like below

string s = new string('~',25);
int ind = 5;
s[ind] = 'A';

it gives an error
Property or indexer 'string.this[int]' cannot be assigned to -- it is read
so what is the problem, and how can i fix it.

解决方案

Strings are immutable - you can't change an existing one.

Two options:

  • Use StringBuilder, e.g.

    StringBuilder builder = new StringBuilder(new string('~', 25));
    builder[5] = 'A';
    string result = builder.ToString();
    

  • Build a new string from a char array:

    char[] chars = new string('~', 25).ToCharArray();
    chars[5] = 'A';
    string result = new string(chars);
    

In both cases you could populate the mutable data without building a new string to start with if you want - that would involve more code, but would probably be more efficient.

Alternatively, you can take substrings and concatenate them together, as per another answer ...there are basically lots of ways of tackling this. Which one is appropriate will depend on your actual use case.

这篇关于如何改变字符串的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆