2012-04-18 31 views

回答

88

可能性:

  • 使用String.equals()

    if (some_string.equals("john") || 
        some_string.equals("mary") || 
        some_string.equals("peter")) 
    { 
    } 
    
  • 使用正則表達式:

    if (some_string.matches("john|mary|peter")) 
    { 
    } 
    
  • 商店字符串列表來對集合中的匹配和搜索的集合:

    Set<String> names = new HashSet<String>(); 
    names.add("john"); 
    names.add("mary"); 
    names.add("peter"); 
    
    if (names.contains(some_string)) 
    { 
    } 
    
1

號,其檢查一樣,如果字符串是"john" OR "mary" OR "peter" OR "etc."

你應該檢查使用||

像,, if(str.equals("john") || str.equals("mary") || str.equals("peter"))

+0

薩米爾,就是個僞代碼:) – sandalone 2012-04-19 08:21:52

2

您目前的實現是正確的。建議是不可能的,但僞代碼將實施多個equal()調用和||

+0

感謝。我用術語pseudo來表示它不是我的代碼的摘錄 – sandalone 2012-04-18 11:08:34

4

保持可接受值的HashSet,並檢查是否存在你的字符串使用contains方法:

Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {"john", "mary", "peter"})); 
if (accept.contains(some_string)) { 
    //... 
} 
0
Pattern p = Pattern.compile("tom"); //the regular-expression pattern 
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with 

while (m.find()) { 
    //do something??? 
} 

使用正則表達式來也許找到一個匹配?

或創建一個數組

String[] a = new String[]{ 
     "tom", 
     "bob", 
     "harry" 
}; 

if(a.contains(stringtomatch)){ 
    //do something 
} 
0

你也可以使用switch語句。例如

switch(yourString) 
{ 
    case "john": 
      //do something for john 
    case "mary": 
      //do something for mary 
} 
+3

'對於低於1.7的源級別,無法切換String類型的值。由於Android不支持Java 1.7,因此只允許使用可轉換的int值或枚舉常量,但此解決方案無效。 – WarrenFaith 2012-04-18 11:21:50

+0

如果兩種情況都屬實,該怎麼辦? – 2016-08-22 18:07:43

21
if (Arrays.asList("John", "Mary", "Peter").contains(name)) { 
} 
  • 這不是一樣快,使用一組準備,但執行並不比使用或更糟。
  • 當名稱爲NULL時,不會崩潰(與Set相同)。
  • 我喜歡它,因爲它看起來乾淨