java For 循环在字符串中搜索单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15480811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:44:36  来源:igfitidea点击:

For loop to search for word in string

java

提问by Bob

I can't seem to find the syntax needed for the for loop in this method. I am looking to iterate through the words in the string suit.

我似乎无法在此方法中找到 for 循环所需的语法。我希望遍历 string 中的单词suit

EDIT: one thing to note is that cardArray is a ArrayList.

编辑:需要注意的一件事是 cardArray 是一个 ArrayList。

public String getSuit(int card){
    String suit = cardArray.get(card);
    for (String word : suit){
        if (word.contains("SPADES")){
            suit = "SPADES";            
        }
    }
    return suit;
}

回答by NPE

You could use

你可以用

for (String word : suit.split(" ")) {

to split on every space character (U+0020).

拆分每个空格字符 (U+0020)

Alternatively:

或者:

for (String word : suit.split("\s+")) {

This splits on every sequence of whitespace character (this includes tabs, newlines etc).

这会拆分每个空白字符序列(包括制表符、换行符等)。

回答by nickb

Try splitting the string on whitespace:

尝试在空格上拆分字符串:

String suit = cardArray.get(card);
for (String word : suit.split("\s+")){
    if (word.contains("SPADES")){
        suit = "SPADES";            
    }
}

回答by John Kane

Why not use an enum for suit, and add it to your Card class or something a bit more Object Oriented? You could even have an Abstract class card or an interface card which would let you add what ever logic was needed inside the Card instance itsself instead of iterating doing string comparisons.

为什么不为花色使用枚举,并将其添加到您的 Card 类或更多面向对象的类中?你甚至可以有一个抽象类卡或一个接口卡,它可以让你在 Card 实例本身中添加任何需要的逻辑,而不是迭代进行字符串比较。

However: String.split(String regex)should work, just choose the appropriate regular expression.

但是:String.split(String regex)应该可以工作,只需选择适当的正则表达式即可

回答by msam

If all you want to do is replace the strings that contain "SPADES":

如果您只想替换包含“SPADES”的字符串:

public String getSuit(int card){
    String suit = cardArray.get(card);
    if (suit.contains("SPADES")){
        cardArray.set(card, "SPADES");            
    }
    return suit;
}

If you want to split the string suitfor some other reason then see the other answers

如果您suit出于其他原因想拆分字符串,请参阅其他答案