以下代码中发生的内部操作究竟是什么
public string s= "vinaysagarreddy";
public int n=1234;
public void RString()
{
string rs="vinaysagaarreddy";
for(int i=s.Length-1;i>=0;i--)
rs[i]=rs[i]+s[i];
}
广告rs=rs+s[i]
正在运作但
rs[i]=rs[i]+s[i];
说我们不能隐式地将int转换为字符串,因为它们在这里被视为字符数组。
我需要这两个陈述的内部操作
rs=rs+s[i]
rs[i]=rs[i]+s[i];
答案 0 :(得分:0)
您正在尝试更改String
不可变另一个问题是Char + Char == int
,因此需要强制:
public void RString() {
string rs = "vinaysagaarreddy";
// <- Error! rs is a string and so immutable; "rs[i] =" is not allowed
for(int i = s.Length - 1;i >= 0; i--)
rs[i] = rs[i] + s[i]; // Char + Char == int; so "rs[i] + s[i]" is int
...
使用StringBuilder
创建/更改字符串
public void RString() {
StringBuilder sb = new StringBuilder("vinaysagaarreddy");
// sb is a StringBuilder : OK to change
for(int i = s.Length - 1;i >= 0; i--)
sb[i] = (Char) (sb[i] + s[i]); // <- Char + Char == int; cast required
String rs = sb.ToString();
...
P.S。请格式化你的代码 - 它很难阅读