我有一个例子。
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];
}但是compare函数不起作用,那么我还可以使用什么其他函数呢?
发布于 2012-06-20 01:57:15
听起来你可以直接使用:
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);发布于 2012-06-20 01:57:56
这应该是可行的:
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];
}发布于 2012-06-20 02:06:15
尝试使用正则表达式(首先替换为"A“,然后替换为"a":
string result = Regex.Replace("Àpple", "([ÀÁÂÄ])", "A", RegexOptions.None);然后你也可以对"a“做同样的事情。
https://stackoverflow.com/questions/11106565
复制相似问题