替换字符串C#不工作
问题描述:
我有两个字符串变量分别命名为X和Y.我想要的是从Y变量中替换X字符串。我使用的命令string.replace没有任何东西通过。 我使用的代码如下所示,由于 斯塔夫罗斯 Afxentis替换字符串C#不工作
string Y= string.Empty;
string X= string.Empty;
Y= get_y_value(...); // my method to get string y
X= get_x_vale(...); // my method to get string X
Y= Y.Replace(X, "");
// i also used Y= Y.Replace(X.ToString(), "");
// but the result is the same
答
替换是用来改变另一个字符串内的“字”。像这样:
string badString = "Can I has the code";
string goodString = badString.Replace("has", "have");
你最大的问题是两个字符串都是空的。
答
的代码应该工作得很好,因为你是用0长度的字符串替换它,它会删除串X,可能有两个原因,为什么这是行不通的, 1)X不以y 2中)你没“T打印或显示已更新的ÿ
答
最后我用下面的代码,其中,i转换的字符串为char阵列和我删除了不需要的文本..以下伪代码:
int i=0;
while ((i<Y.Length) && (counter<1))
{
//ignore part of the string
// and save the position of the char array i want
}
while (poss<Y.Length)
{
new_ch[poss] = ch[poss] //save the array to new char array
}
string y_new = new string(new_ch);
然后X中未发现Y,甚至没有。它的工作原理与其记录的一样。 – user2864740 2014-10-04 22:30:56
您只需将'Y'设置为'string.Empty' ...在Replace()后它仍然是'string.Empty'。你删除了一些代码吗?在调用'Replace()'之前,什么值存储在'X'和'Y'中? – 2014-10-04 22:32:54
如果您发布实际代码/更多代码,可能会有所帮助。用你所显示的代码,无论X是什么,Y总是'string.Empty',所以你不可能取代任何东西。 – 2014-10-04 22:33:32