How to check if a string contains a substring containing spaces?

前端 未结 6 1765
一个人的身影
一个人的身影 2020-12-18 12:26

Say I have a string like this in java:

\"this is {my string: } ok\"

Note, there can be any number of white spaces in between the various characters. How do I

相关标签:
6条回答
  • 2020-12-18 13:05

    The easiest thing to do is to strip all the spaces from both strings.

    return stringToSearch.replaceAll("\s", "").contains(
      stringToFind.replaceAll("\s", ""));
    
    0 讨论(0)
  • 2020-12-18 13:13

    For this purpose you need to use String#contains(CharSequence).

    Note, there can be any number of white spaces in between the various characters.

    For this purpose String#trim() method is used to returns a copy of the string, with leading and trailing whitespace omitted.

    For e.g.:

    String myStr = "this is {my string: } ok";
    if (myStr.trim().contains("{my string: }")) {
        //Do something.
    } 
    
    0 讨论(0)
  • 2020-12-18 13:18

    If you are looking to see if a String contains another specific sequence of characters then you could do something like this :

    String stringToTest = "blah blah blah";
    
    if(stringToTest.contains("blah")){
        return true;
    }
    

    You could also use matches. For a decent explanation on matching Strings I would advise you check out the Java Oracle tutorials for Regular Expressions at :

    http://docs.oracle.com/javase/tutorial/essential/regex/index.html

    Cheers,

    Jamie

    0 讨论(0)
  • 2020-12-18 13:20

    Look for the regex

    \{\s*my\s+string:\s*\}
    

    This matches any sequence that contains

    1. A left brace
    2. Zero or more spaces
    3. 'my'
    4. One or more spaces
    5. 'string:'
    6. Zero or more spaces
    7. A right brace

    Where 'space' here means any whitespace (tab, space, newline, cr)

    0 讨论(0)
  • 2020-12-18 13:25

    If you have any number of white space between each character of your matching string, I think you are better off removing all white spaces from the string you are trying to match before the search. I.e. :

    String searchedString = "this is {my string: } ok";
    String stringToMatch = "{my string: }";
    boolean foundMatch = searchedString.replaceAll(" ", "").contains(stringToMatch.replaceAll(" ",""));
    
    0 讨论(0)
  • 2020-12-18 13:25

    Put it all into a string variable, say s, then do s.contains("{my string: }); this will return true if {my string: } is in s.

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