2010-09-16 40 views
2

我需要糾正字符串中不需要的字符。 不需要的字符:的 「i」的代替更正字符串中的字符?

「C」而不是「C」,「I」 「U」代替,而不是「G」 「○」「ü」 「G」代替「 ö「 」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; 
    } 

我該如何執行此任務?

回答

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(); 
} 
+0

它不會工作,因爲他會調用text.Replace每一次。只有最後一個匹配的字符會被替換。 – 2010-09-16 12:55:22

+0

對。在寫答案之前沒有看過代碼。 – 2010-09-16 12:56:15

+0

不是。這沒有解決我的問題。我不知道問題在哪裏。 – beratuslu 2010-09-16 12:56:21

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

也許它不工作,因爲你試圖直接匹配字符的。我的方法可行,我使用unicode代碼來匹配特殊字符,使用unicode chart。您不必遍歷每個字符,因爲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; 
} 

我已經測試了這個與你的特殊字符,它對我來說工作得很好。

0

它看起來像你來自C背景,並沒有認爲字符串在.net(以及Java)中是不可變的。

你的函數可以返回一個新的字符串,所有的字符被替換爲替換,但原始字符串將保持不變。

基本上,你可以採取klausbyskov的版本但是,與其說這是這樣的:

UrlCorrection(url); 

你必須調用如

url=UrlCorrection(url);