Chea Indian
Chea Indian

Reputation: 697

How do I check whether input string contains any spaces?

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()?

Upvotes: 37

Views: 195614

Answers (10)

Brent K.
Brent K.

Reputation: 1076

Basic Match

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.

Performance Improvement

The regex above is easy to remember and uses a somewhat simple syntax. Unfortunately, it uses a "greedy" match, and will continue searching after it finds the first match, trying to find the longest match. This may be fine on short data sets, but could cause performance problems on large input data sets.

To solve this, we want the match to stop looking on the first match. So, we switch to the lazy match by adding the '?' after the ".*". We also want parentheses around each match so each wildcard is grouped into a single entity.

str.matches("(.*?)\\s(.*?)")
  • The first "(.*?) says there can be zero or more characters in front of the space; stop looking when you have found such a match.
  • The "\\s" says it must contain any whitespace character.
  • The last "(.*?) says there can be zero or more characters after that first space; stop looking when you have found such a match.

Test Code

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));
}

Upvotes: 11

Nilesh Mahant
Nilesh Mahant

Reputation: 35

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 ++;
}

Upvotes: 0

SaPropper
SaPropper

Reputation: 523

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

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

Example:

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

Upvotes: 0

Subashini Piuamli
Subashini Piuamli

Reputation: 1

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");
    }
}

Upvotes: 0

Jeanne vie
Jeanne vie

Reputation: 524

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
 }

Upvotes: 0

Cagatay Kalan
Cagatay Kalan

Reputation: 4126

If you will use Regex, it already has a predefined character class "\S" for any non-whitespace character.

!str.matches("\\S+")

tells you if this is a string of at least one character where all characters are non-whitespace

Upvotes: 16

jingx
jingx

Reputation: 4014

if (str.indexOf(' ') >= 0)

would be (slightly) faster.

Upvotes: 4

Razvan
Razvan

Reputation: 10093

If you really want a regex, you can use this one:

str.matches(".*([ \t]).*")

In the sense that everything matching this regex is not a valid xml tag name:

if(str.matches(".*([ \t]).*")) 
      print "the input string is not valid"

Upvotes: 2

Kendall Frey
Kendall Frey

Reputation: 44316

Why use a regex?

name.contains(" ")

That should work just as well, and be faster.

Upvotes: 83

Paul Creasey
Paul Creasey

Reputation: 28824

string name = "Paul Creasey";
if (name.contains(" ")) {

}

Upvotes: 5

Related Questions