2011-11-28 71 views
1

所以我想通過一個字符串來查找它是否包含我正在尋找的子字符串。這是我寫了算法:Java通過字符串搜索

//Declares the String to be searched 
    String temp = "Hello World?"; 

    //A String array is created to store the individual 
    //substrings in temp 
    String[] array = temp.split(" "); 

    //Iterates through String array and determines if the 
    //substring is present 
    for(String a : array) 
    { 
     if(a.equalsIgnoreCase("hello")) 
     { 
      System.out.println("Found"); 
      break; 
     } 
     System.out.println("Not Found"); 
    } 

這個算法適用於「你好」,但我不知道如何得到它爲「世界」的工作,因爲它附加了一個問號。

感謝您的幫助!

+0

你的意思是「世界」應與「世界?」 ???? – corlettk

+0

是的,我希望它忽略問號。 – LTH

回答

6

請看: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

String.contains(); 

要獲得containsIgnoreCase(),你必須讓你的搜索內容和你的字符串toLowerCase()。

看看這個答案: How to check if a String contains another String in a case insensitive manner in Java?

return s1.toLowerCase().contains(s2.toLowerCase()); 

這也將是真實的:世界的 戰爭,因爲它會發現世界。如果你不想要這種行爲,你必須像@Bart Kiers所說的那樣改變你的方法。

+0

'.contains()'是casesensetive,而OP使用'equalsIgnoreCase'。 http://stackoverflow.com/questions/86780/is-the-contains-method-in-java-lang-string-case-sensitive可能是有用的 – Vladimir

+1

你是對的。但是在相同的位置,你可以找到LowCase()的方法。但我會解決我的答案。 –

+1

這在'temp =「hell worldie」''hell'或'worldie'(取決於如果s1是用戶控制的字符串還是輸入)的情況下會產生錯誤。 –

4

分割上,而不是執行以下操作:

"[\\s?.!,]" 

它匹配任何空間字符,問號,點,感嘆號或逗號(添加更多的字符,如果你喜歡)。

或者做一個temp = temp.toLowerCase()然後temp.contains("world")

0

您可能需要使用:

String string = "Hello World?"; 
boolean b = string.indexOf("Hello") > 0;   // true 

要忽略的情況下,必須使用正則表達式。

b = string.matches("(?i).*Hello.*"); 

一個更多的變化忽略的情況將是:

// To ignore case 
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true 
+0

要忽略大小寫,可以使用正則表達式** CAN ** ....而不是「必須」;-) – corlettk