2012-09-06 17 views
1

我正在使用java servlets。在我的數據庫中,一些字符串包含字符Å,Ä和Ö。當我檢查那些包含這些特殊字符的字符串時,它總是假的。我如何檢查一個字符串是否包含這些特殊字符。我正在使用Eclipse。提前致謝。如何檢查一個字符串是否包含java servlet中的Å,Ä或Ö字符?

+0

您是否正確地從數據庫中獲取字符串?即具有特殊字符? – JoeG

+0

請張貼您的Servlet代碼的相關部分,以便我們可以看到您到目前爲止所嘗試的內容以及可能出錯的地方。 –

+0

@JoeG我正在使用谷歌應用程序引擎進行數據存儲。在我看到的日誌中?而不是Å,Ä和Ö。但是,當我去數據存儲和檢查存儲的字符串,然後正確顯示Å,Ä和Ö。 – Piscean

回答

0

這些是擴展的ASCII字符。

byte[] data=new byte[1]; 
data[0]=(byte)197; 197 is for Å 
String char1=new String(data,"ISO-8859-1"); 

您可以像上面那樣創建字符串「char1」,然後與目標字符串進行比較。

代碼四處查找:

for(int i=127;i < 256;i++) 
     { 
      byte[] char= new byte[1]; 
      char[0]= (byte)i; 
      System.out.println("Data : "+char+","+ 
new String(char, "ISO-8859-1")+","+i); //'i' will give u code. 197 is for Å so on. 
     } 

看到這個表,字符集由Java SE 6的支持:來源:http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set 
ISO-8859-1  ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 
UTF-8 Eight-bit UCS Transformation Format 
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order 
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order 
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark 
+2

這個答案如何回答OP問題? – Santosh

+0

@Santosh我已經更新了我的答案! –

0

編碼輸入流必須是正確的。 Java字符串已經被編碼。看看下面的例子,當讀者使用inputString工作得很好。但是如果外部輸入流字節需要編碼給閱讀器(因此java.lang.String)。當你不傳遞任何東西時,Java使用依賴於運行時平臺的默認字符集。當你知道charset特定於應用程序時,你應該將它作爲參數傳遞。要小心,因爲某些字符集提供一個字節(ASCII),有些提供一個或兩個字節(UTF8),有些提供兩個字節(UTF16)。

// String charset = "UTF-8"; 
    // Reader inputReader = new InputStreamReader(new FileInputStream("xxxx"), charset); 
    String inputString = "Å, Ä or Ö"; 
    StringReader stringReader = new StringReader(inputString); 
    Reader reader = stringReader; 
    int data = reader.read(); 
    while (data != -1) { 
     char dataChar = (char) data; 
     int codeChar = (int) data; 
     System.out.println("char=" + dataChar + ", code=" + codeChar); 
     data = reader.read(); 
    } 
    String toReplace = "Å"; 
    String stringAfter = inputString.replace(toReplace, "B"); 
    System.out.println(stringAfter); 

    // prints: 

    char=Å, code=197 
    char=,, code=44 
    char= , code=32 
    char=Ä, code=196 
    char= , code=32 
    char=o, code=111 
    char=r, code=114 
    char= , code=32 
    char=Ö, code=214 
    B, Ä or Ö 
0

可以使用string.contains(S) method.See樣品;

String x = "aaa Å bbb"; 
    if(x.contains("Å")){ 
     System.out.println("OK"); 
    } 
相關問題