2013-04-11 111 views
1

我遇到了字符串比較的一些問題,字符串是由Request.queryString接收的字符串和文件.resx中的一行。C#字符串比較不起作用

代碼收到Request.queryString到一個名爲q變量,然後它去一個函數來比較,如果線路中有q值:

 while ((line = filehtml.ReadLine()) != null) 
     { 
      if (line.ToLower().Contains(q.ToLower().ToString())) 
       HttpContext.Current.Response.Write("<b>Content found!</b>"); 
      else 
       HttpContext.Current.Response.Write("<b>Content not found!</b>"); 
     } 

正如它在靜態文件搜索,特殊字符必須是審議並seraching爲:iber&ecirc;,即從q到來,與iber&#234;是從行來:Iberê例如,因爲.Contains.IndexOf.LastindexOf是比較不返回true。

考慮到我已經嘗試使用ResXResourceReader(無法通過Visual Studio找到),ResourceReader和ResourceManager(這些我無法通過要讀取的路徑設置靜態文件)。


編輯:

問題解決了。有中SpecialChars一個實例,覆蓋q值與EntitiesEncode方法

+4

所以你說的是字符串「iber ê」不等於「iber ê」?這是正確的 - 我很驚訝,你感到驚訝... – 2013-04-11 15:23:29

+1

我敢肯定,你將需要將數據轉換爲'byte []'並比較這些數據。 – 2013-04-11 15:24:01

回答

3

的問題是ê字符在兩個字符串逃過一劫。所以,如果你做了這樣的事情,它不會工作:

 string line = "sample iber&ecirc; text"; 
     string q = "iber&#234;"; 
     if (line.Contains(q)) { 
      // do something 
     } 

你需要隱藏字符串。在System.Web組件中使用HttpUtility。這將工作:

 line = System.Web.HttpUtility.HtmlDecode(line); 
     q = System.Web.HttpUtility.HtmlDecode(q); 
     if (line.Contains(q)) { 
      // do something 
     } 

如建議通過以下@ r3bel,如果你使用.NET 4級或以上,你也可以使用System.Net.WebUtility.HtmlDecode,所以你並不需要一個額外的程序集引用。

+2

寫在這裏:http://stackoverflow.com/questions/122641/how-can-i-decode-html-characters-in-c,你可以在.NET 4.0+中使用WebUtility.HtmlDecode :) – r3bel 2013-04-11 15:30:29

+0

@ r3bel The好的一點是你不需要對'System.Web.dll'的程序集引用。 – 2013-04-11 15:35:49

+0

@caerolus - 謝謝你的回答。我嘗試解碼,但'HttpUtility.HtmlDecode(q)= iber ê'和'HttpUtility.HtmlDecode(line)= iber ê'。 – 2013-04-11 15:56:56