C# - 高效搜索并替换字符串中的char数组

时间:2012-06-19 17:55:05

标签: c# asp.net

我有例如

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];
}

但是比较功能不起作用,那么我可以使用其他功能吗?

3 个答案:

答案 0 :(得分:5)

听起来你可以只使用:

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);

答案 1 :(得分:2)

这应该有效:

for (int i = 0; i < str.Length; i++)
{ 
    if(A.Contains(str[i]))
        strNew += 'A'
    else if(a.Contains(str[i])) 
          strNew +='a'
    else
        strNew += str[i];
}

答案 2 :(得分:0)

尝试使用正则表达式(首先替换为&#34; A&#34;然后使用&#34; a&#34;:

string result = Regex.Replace("Àpple", "([ÀÁÂÄ])", "A", RegexOptions.None);

然后你可以为&#34; a&#34;。

做同样的事情
相关问题