2014-09-10 120 views
1

我正在檢查是否可用的句子或不是。我想檢查java字符串。網頁是一個字符串變量,該代碼是在這裏Java字符串檢查

page="Paint, Body & Trim : Body : Moldings : Sunroof"; 



if(page.contains("of")) 
{ 
} 
else 
{ 
} 

在上面的例子天窗的問題有「的」這樣的循環給予如此。但我不想用「的」來採取措辭。請幫助我。

回答

1

您可以使用Scanner" : "分隔符:

String page="Paint, Body & Trim : Body : Moldings : Sunroof"; 

boolean contains(Scanner scan, word){ 
    scan.useDelimiter(" : "); 
    while(in.hasNext()) 
     if(in.next().equals(word) return true; 
    return false; 
} 

,然後作出這樣System.out.println(contains(new Scanner(page), "of");

電話本是打印false

4

只要改變這個

if(page.contains("of")) 

if(page.contains(" of ")) 

編輯:如果句子開始就考慮或結束 「的」:

if(page.contains(" of ") || page.startsWith("of ") || page.endsWith(" of")) 
+4

如果「of」在字符串的開頭,即在開始時沒有字符串,這將失敗。 – 2014-09-10 09:34:56

+0

@ZaheerAhmed編輯根據您的意見,謝謝! – 2014-09-10 09:46:31

+1

如果「of」在標點符號之前,這將失敗。 – 2014-09-10 09:48:20

3

你可以做它以這種方式。使用equals()代替

String page="Paint, Body & Trim : Body : Moldings : Sunroof"; 
    for (String i:page.split(" ")){ 
     if("of".equals(i)){ 

     } 
    } 
1

嘗試if(page.contains(" of "))這樣將只需要「的」,而不是串與串詞。

0

,或者如果你只是看單詞的整個另一種方式:

String page="Paint, Body & Trim : Body : Moldings : Sunroof"; 
StringTokenizer st2 = new StringTokenizer(str, " ");//space 

     while (st2.hasMoreElements()) { 
      if((st2.nextElement().equals("of")){ 
       //whatever.. 
      } 
     } 
0

你可以做

if (page.matches(".*\\bof\\b.*")) { 
0

這裏需要使用正則表達式,將可以很容易否則你需要添加很多檢查:

System.out.println(str.matches(".*\\bof\\b.*")); //will return true 

這是Demo

0

前後搜索字符串後面添加空格, 即

if(page.contains(" of ")){ 
} 

另一種方式是拆分句子的空間分隔符,但在這裏你需要循環throgh字符串數組。

1

做到這一點是使用正則表達式的最好方法:

page.matches(".*\\b[Oo][Ff]\\b.*") 

.*表示「任何字符零次或多次」。 \\bword boundary[Oo]表示字符'O',大寫或小寫。

這裏有一些測試用例:

String page = "Paint, Body & Trim : Body : Moldings : Sunroof"; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // false 
page = "A piece of cake"; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // true 
page = "What I'm made of"; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // true 
page = "What I'm made of."; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // true 
page = "What I'm made of, flesh"; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // true 
page = "Of the Night"; 
System.out.println(page.matches(".*\\b[Oo][Ff]\\b.*")); // true 

匹配「的」(與之前和之後的空格)將在案件「的」哪裏是開頭,在最後一個標點前不行, ,...