2013-07-26 54 views
1

如何檢查字符串是否僅包含字符,可以在ISO 8859-1中成功編碼?換句話說 - 如何在字符串中找到「非法」/「不兼容ISO 8859-1」字符?檢查字符串是否僅包含有效的ISO 8859-1字符

+0

會[幫助] [這篇文章](http://stackoverflow.com/questions/1025332/determine-a-strings-encoding-in-c-sharp)? –

+0

@MechanicalObject:可能不是,如果它已經是C#字符串(而不是原始字節)。 – Thilo

回答

12

試試這個:

private static bool IsValidISO(string input) 
    { 
     byte[] bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(input); 
     String result = Encoding.GetEncoding("ISO-8859-1").GetString(bytes); 
     return String.Equals(input, result); 
    } 

這個答案是基於Java的這個問題的回答(我的代碼是C#相當於): http://www.velocityreviews.com/forums/t137810-checking-whether-a-string-contains-only-iso-8859-1-chars.html

+0

這看起來比我的想法更好。感謝您的回答! – netblognet

+1

@netblognet不客氣!我也看了你的代碼,但它看起來很「危險」,因爲你不能100%確定非ISO字符會給出問號。我的代碼也更快。 – ProgramFOX

0

您可以設置數組或有效字符列表,然後遍歷字符串以檢查它們是否存在於您的有效字符列表中。該列表可以通過向其添加所有有效的拉丁字符1來創建。

0

我想出了這個主意。這可能嗎?

private static bool IsValidISO(string input) 
    { 
     foreach (char c in input) 
     { 
      Encoding iso = Encoding.GetEncoding("ISO-8859-1"); 
      Encoding utf8 = Encoding.UTF8; 

      byte[] isoBytes = iso.GetBytes(c.ToString()); 
      byte[] utfBytes = Encoding.Convert(iso, utf8, isoBytes); 

      string convertedC = utf8.GetString(utfBytes); 
      if (c != '?' && convertedC == "?") 
       return false; 
     } 
     return true; 
    } 
相關問題