我有例如
string str ='Àpple';
string strNew="";
char[] A = {'À','Á','Â','Ä'};
char[] a = {'à','á','â','ä'};
Run Code Online (Sandbox Code Playgroud)
我想通过str查看是否找到替换为Ascii代码'A'.所以结果应该是:
strNew = 'Apple';
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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];
}
Run Code Online (Sandbox Code Playgroud)
但是比较功能不起作用,那么我可以使用哪些其他功能呢?
听起来你可以使用:
if (A.Contains(str[i]))
Run Code Online (Sandbox Code Playgroud)
但肯定有更有效的方法.特别是,避免循环中的字符串连接.
我的猜测是有一些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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6898 次 |
| 最近记录: |