For loop to search for word in string

后端 未结 4 1239
孤城傲影
孤城傲影 2021-01-18 11:12

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.

EDIT: one thing t

相关标签:
4条回答
  • 2021-01-18 11:19

    Try splitting the string on whitespace:

    String suit = cardArray.get(card);
    for (String word : suit.split("\\s+")){
        if (word.contains("SPADES")){
            suit = "SPADES";            
        }
    }
    
    0 讨论(0)
  • 2021-01-18 11:20

    You could use

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

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

    Alternatively:

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

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

    0 讨论(0)
  • 2021-01-18 11:23

    If all you want to do is replace the strings that contain "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 suit for some other reason then see the other answers

    0 讨论(0)
  • 2021-01-18 11:33

    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.

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

    0 讨论(0)
提交回复
热议问题