How do I check whether input string contains any spaces?

Viewed 160206

I have a input dialog that asks for XML element name, and I want to check it to see if it has any spaces.

can I do something like name.matches()?

10 Answers

A simple answer, along similar lines to the previous ones is:

str.matches(".*\\s.*")
  • The first ".*" says that there can be zero or more instances of any character in front of the space.
  • The "\\s" says it must contain any whitespace character.
  • The last ".*" says there can be zero or more instances of any character after the space.

When you put all those together, this returns true if there are one or more whitespace characters anywhere in the string.

Here is a simple test you can run to benchmark your solution against:

boolean containsWhitespace(String str){
    return str.matches(".*\\s.*");
}

String[] testStrings = {"test", " test", "te st", "test ", "te   st", 
                        " t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
        System.out.println( "Does \"" + eachString + "\" contain whitespace? " + 
                             containsWhitespace(eachString));
}

This is tested in android 7.0 up to android 10.0 and it works

Use these codes to check if string contains space/spaces may it be in the first position, middle or last:

 name = firstname.getText().toString(); //name is the variable that holds the string value

 Pattern space = Pattern.compile("\\s+");
 Matcher matcherSpace = space.matcher(name);
 boolean containsSpace = matcherSpace.find();

 if(constainsSpace == true){
  //string contains space
 }
 else{
  //string does not contain any space
 }

You can use this code to check whether the input string contains any spaces?

public static void main(String[]args)
{
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the string...");
    String s1=sc.nextLine();
    int l=s1.length();
    int count=0;
    for(int i=0;i<l;i++)
    {
        char c=s1.charAt(i);
        if(c==' ')
        {
        System.out.println("spaces are in the position of "+i);
        System.out.println(count++);
        }
        else
        {
        System.out.println("no spaces are there");
    }
}

To check if a string does not contain any whitespaces, you can use

string.matches("^\\S*$")

Example:

"name"        -> true
"  "          -> false
"name xxname" -> false

You can use regex ā€œ\\sā€

Example program to count number of spaces (Java 9 and above)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {

    Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);        
    Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");        

    long matchCount = matcher.results().count();   
 
    if(matchCount > 0) 
      System.out.println("Match found " + matchCount + " times.");           
    else 
      System.out.println("Match not found");        
  }
}

For Java 8 and below you can use matcher.find() in a while loop and increment the count. For example,

int count = 0;
while (matcher.find()) {
  count ++;
}
Related