[java] How can I find whitespace in a String?

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 = "test word";

This question is related to java string space

The answer is


package com.test;

public class Test {

    public static void main(String[] args) {

        String str = "TestCode ";
        if (str.indexOf(" ") > -1) {
            System.out.println("Yes");
        } else {
            System.out.println("Noo");
        }
    }
}

import java.util.Scanner;
public class camelCase {

public static void main(String[] args)
{
    Scanner user_input=new Scanner(System.in);
    String Line1;
    Line1 = user_input.nextLine();
    int j=1;
    //Now Read each word from the Line and convert it to Camel Case

    String result = "", result1 = "";
    for (int i = 0; i < Line1.length(); i++) {
        String next = Line1.substring(i, i + 1);
        System.out.println(next + "  i Value:" + i + "  j Value:" + j);
        if (i == 0 | j == 1 )
        {
            result += next.toUpperCase();
        } else {
            result += next.toLowerCase();
        }

        if (Character.isWhitespace(Line1.charAt(i)) == true)
        {
            j=1;
        }
        else
        {
            j=0;
        }
    }
    System.out.println(result);

You can basically do this

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

You must write boolean method.Whitespace char is 32.


String str = "Test Word";
            if(str.indexOf(' ') != -1){
                return true;
            } else{
                return false;
            }

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

public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

This will tell if you there is any whitespaces:

Either by looping:

for (char c : s.toCharArray()) {
    if (Character.isWhitespace(c)) {
       return true;
    }
}

or

s.matches(".*\\s+.*")

And StringUtils.isBlank(s) will tell you if there are only whitepsaces.


Use Apache Commons StringUtils:

StringUtils.containsWhitespace(str)

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:


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.


You could use Regex to determine if there's a whitespace character. \s.

More info of regex here.


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

Use this code, was better solution for me.

public static boolean containsWhiteSpace(String line){
    boolean space= false; 
    if(line != null){


        for(int i = 0; i < line.length(); i++){

            if(line.charAt(i) == ' '){
            space= true;
            }

        }
    }
    return space;
}

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"


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to space

How to create string with multiple spaces in JavaScript Removing body margin in CSS What is the symbol for whitespace in C? Using tr to replace newline with space CSS: how to add white space before element's content? Regular expression to allow spaces between words UL has margin on the left EXCEL VBA Check if entry is empty or not 'space' How do I make Java register a string input with spaces? Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>