我需要纠正字符串中不需要的字符。 不需要的字符:
“c”而不是“ç” “我”代替“ı” “你”而不是“ü” “g”而不是“ğ” “o”而不是“ö” “s”而不是“ş”
我写过这个方法。但它不起作用。
public string UrlCorrection(string text)
{
text = (text.ToLower()).Trim();
var length = text.Length;
char chr;
string newtext="";
for (int i = 0; i < length; i++)
{
chr = text[i];
switch (chr)
{
case 'ç':
newtext = text.Replace("ç", "c");
break;
case 'ı':
newtext = text.Replace("ı", "i");
break;
case 'ü':
newtext = text.Replace("ü", "u");
break;
case 'ğ':
newtext = text.Replace("ğ", "g");
break;
case 'ö':
newtext = text.Replace("ö", "o");
break;
case 'ş':
newtext = text.Replace("ş", "s");
break;
default:
break;
}
}
newtext = text;
return text;
}
我如何实现此任务?
答案 0 :(得分:5)
基本上你可以这样做:
newtext = text.Replace("ç", "c");
newtext = newtext.Replace("ı", "i");
newtext = newtext.Replace("ü", "u");
newtext = newtext.Replace("ğ", "g");
newtext = newtext.Replace("ö", "o");
newtext = newtext.Replace("ş", "s");
无需开关/外壳/索引疯狂。
答案 1 :(得分:2)
这样做:
public string UrlCorrection (string text)
{
StringBuilder correctedText = new StringBuilder (text);
return correctedText.Replace("ç", "c")
.Replace("ı", "i")
.Replace("ü", "u")
.Replace("ğ", "g")
.Replace("ö", "o")
.Replace("ş", "s")
.ToString ();
}
答案 2 :(得分:1)
也许它不起作用,因为你试图直接匹配char。我的方法有效,我使用unicode代码匹配特殊字符,使用此unicode chart。您不必循环遍历每个char,因为Replace()
替换了
public string UrlCorrection(string text)
{
text = text.ToLower().Trim();
text = text
.Replace('\u00E7','c')
.Replace('\u0131','i')
.Replace('\u00FC','u')
.Replace('\u011F','g')
.Replace('\u00F6','o')
.Replace('\u015F','s');
return text;
}
我用你的特殊字符对它进行了测试,它对我来说效果很好。
答案 3 :(得分:0)
看起来你来自C背景并且没有考虑到.net(以及Java)中的字符串是不可变的。
您的函数可以返回一个新字符串,所有字符都替换为其替换字符,但原始字符串将保持不变。
基本上,您可以使用klausbyskov的版本,但不要这样称呼它:UrlCorrection(url);
你必须打电话,例如。
url=UrlCorrection(url);