2016-12-28 101 views
0

找到特定單詞我想檢查特定單詞是否退出或不在字符串中,忽略大小寫。如何從字符串android

我的字符串是 - 「你好世界,Wassup?,好moRNING」。

現在我想檢查一下這個詞 - 「你好世界」。

,所以我曾嘗試以下:

String fullText = "Hello world , Wassup? , good moRNING"; 
String singleWord = "hello world"; 
boolean find; 

if (fullText.matches(singleWord)) { 

    find = True; 
} 

我也試圖與contains,但是這是行不通的。

我怎樣才能找到這個特殊的詞?

+1

嘗試谷歌,看看這裏:http://stackoverflow.com/questions/5091057/how-to-find-a-whole-word-in-a-string-in-java – Flummox

+1

你好,你好是不同 –

+0

除了小寫字母和大寫字母'h'之間的區別(正如@ AdityaVyas-Lakhan指出的那樣),'contains()'應該有效。 'matches()'不適合,因爲它(a)需要一個正則表達式,並且(b)只在整個字符串匹配正則表達式時才返回真,也就是說,在前後不包含更多字符。 –

回答

3

你可以用這兩個字符串轉換爲常見的情況,然後利用indexOf或以其他方式匹配的需要利用一個regex.

String fullText = "Hello world , Wassup? , good moRNING"; 
String singleWord = "hello world"; 
boolean find; 



if (fullText.toLowerCase().indexOf(singleWord.toLowerCase()) > -1) { 

    find = true; 
} 
+0

應該工作(在'True'中從首都'T'應用)。如果使用Java 5或更新版本,'contains()'更簡單。 –

+0

@ OleV.V。感謝您指出。我編輯了代碼。 –

2

您可以嘗試將要搜索的句子和字符串(例如,

if (fullText.toLowerCase().matches(singleWord.toLowerCase())) { 
    find = True; 
} 
1

的問題是這樣的:

^h ELLO世界不包含^h ELLO世界因爲它有大寫字母。

使用此:

if (fullText.toLowerCase().matches(singleWord.toLowerCase())) { 
    find = True; 
} 
2
find = fullText.toUpperCase().contains(singleWord.toUpperCase()); 
1

你可以試試這個:

String string = "Test, I am Adam"; 
// Anywhere in string 
b = string.indexOf("I am") > 0;   // true if contains 

// Anywhere in string 
b = string.matches("(?i).*i am.*");  // true if contains but ignore case 

// Anywhere in string 
b = string.contains("AA") ;