How can I find whitespace in a String?

后端 未结 14 1026
感动是毒
感动是毒 2020-12-01 05:08

How can I check to see if a String contains a whitespace character, an empty space or \" \". If possible, please provide a Java example.

For example: String

相关标签:
14条回答
  • 2020-12-01 05:39

    Check whether a String contains at least one white space character:

    public static boolean containsWhiteSpace(final String testCode){
        if(testCode != null){
            for(int i = 0; i < testCode.length(); i++){
                if(Character.isWhitespace(testCode.charAt(i))){
                    return true;
                }
            }
        }
        return false;
    }
    

    Reference:

    • Character.isWhitespace(char)

    Using the Guava library, it's much simpler:

    return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
    

    CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.

    0 讨论(0)
  • 2020-12-01 05:39

    Use org.apache.commons.lang.StringUtils.

    1. to search for whitespaces

    boolean withWhiteSpace = StringUtils.contains("my name", " ");

    1. To delete all whitespaces in a string

    StringUtils.deleteWhitespace(null) = null StringUtils.deleteWhitespace("") = "" StringUtils.deleteWhitespace("abc") = "abc" StringUtils.deleteWhitespace(" ab c ") = "abc"

    0 讨论(0)
  • 2020-12-01 05:44

    I purpose to you a very simple method who use String.contains:

    public static boolean containWhitespace(String value) {
        return value.contains(" ");
    }
    

    A little usage example:

    public static void main(String[] args) {
        System.out.println(containWhitespace("i love potatoes"));
        System.out.println(containWhitespace("butihatewhitespaces"));
    }
    

    Output:

    true
    false
    
    0 讨论(0)
  • 2020-12-01 05:44

    You can basically do this

    if(s.charAt(i)==32){
       return true;
    }
    

    You must write boolean method.Whitespace char is 32.

    0 讨论(0)
  • 2020-12-01 05:48

    You can use charAt() function to find out spaces in string.

     public class Test {
      public static void main(String args[]) {
       String fav="Hi Testing  12 3";
       int counter=0;
       for( int i=0; i<fav.length(); i++ ) {
        if(fav.charAt(i) == ' ' ) {
         counter++;
          }
         }
        System.out.println("Number of spaces "+ counter);
        //This will print Number of spaces 4
       }
      }
    
    0 讨论(0)
  • 2020-12-01 05:50

    For checking if a string contains whitespace use a Matcher and call it's find method.

    Pattern pattern = Pattern.compile("\\s");
    Matcher matcher = pattern.matcher(s);
    boolean found = matcher.find();
    

    If you want to check if it only consists of whitespace then you can use String.matches:

    boolean isWhitespace = s.matches("^\\s*$");
    
    0 讨论(0)
提交回复
热议问题