Find a complete word in a string java

前端 未结 9 2039
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 06:52

I am writing a piece of code in which i have to find only complete words for example if i have

String str = \"today is tuesday\";

and I\'m

相关标签:
9条回答
  • 2021-01-16 07:00
    String str = "today is tuesday";
    
    StringTokenizer stringTokenizer = new StringTokenizer(str);
    
    bool exists = false;
    
    while (stringTokenizer.hasMoreTokens()) {
        if (stringTokenizer.nextToken().equals("t")) {
            exists = true;
            break;
        }
    }
    
    0 讨论(0)
  • 2021-01-16 07:04

    I use a regexps for such tasks. In your case it should look something like this:

    String str = "today is tuesday";
    return str.matches(".*?\\bt\\b.*?"); // returns "false"
    
    String str = "today is t uesday";
    return str.matches(".*?\\bt\\b.*?"); // returns "true"
    

    A short explanation:

    . matches any character, *? is for zero or more times, \b is a word boundary.

    More information on regexps can be found here or specifically for java here

    0 讨论(0)
  • 2021-01-16 07:09

    use a regex like "\bt\b".

    0 讨论(0)
  • 2021-01-16 07:10

    I would recommend you use the "split" functionality for String with spaces as separators, then go through these elements one by one and make a direct comparison.

    0 讨论(0)
  • 2021-01-16 07:12

    I would suggest using this regex pattern1 = ".\bt\b." instead of pattern2 = ".?\bt\b.?" . Pattern1 will help you to match the complete String if 't' occurs in that string rather than the pattern2 which just reaches the string "t" you are searching for and ignores rest of the string. There is not much difference in two approaches and for your particular use case of returning true/false will run fine both the ways. The one I suggested will help you to improvise the regex in case you make further changes in your use case

    0 讨论(0)
  • you can do that by putting a regex which should end with a space.

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