我有
string str ='Àpple';
string strNew="";
char[] A = {'À','Á','Â','Ä'};
char[] a = {'à','á','â','ä'};
我想浏览一下str,看看是否找到了用Ascii代码'A'替换的内容。因此,结果应为:
strNew = 'Apple';
这是我的代码:
for (int i = 0; i < str.Length; i++)
{
if(str[i].CompareTo(A))
strNew += 'A'
else if(str[i].CompareTo(a))
strNew +='a'
else
strNew += str[i];
}
但是比较功能不起作用,那么我还能使用什么其他功能?
最佳答案
听起来您可以使用:
if (A.Contains(str[i]))
但是肯定有更有效的方法可以做到这一点。特别要避免循环中的字符串连接。
我的猜测是,有Unicode规范化方法也不需要您对所有这些数据进行硬编码。我确定我记得在某个地方,围绕编码后备,但是我不能指责它。编辑:我怀疑它在
String.Normalize
周围-至少值得一看。至少,这样会更有效:
char[] mutated = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
// You could use a local variable to avoid calling the indexer three
// times if you really want...
mutated[i] = A.Contains(str[i]) ? 'A'
: a.Contains(str[i]) ? 'a'
: str[i];
}
string strNew = new string(mutated);
关于C#-有效搜索并替换字符串中的char数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11106565/