Hi!

I'd like to check if a string contains spaces:

System.out.println(text2.getText().matches("\\s+"));

This code returns 'false' for both "My string" and "MyString". But I need 'true' for "MySpace". How could I do this? Thanks!

package arrayexample1;
import java.util.Scanner;
public class CountSpaceInString {
    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");
        }
    }

}
}

malli: talking about overkill .

did you read James' reply? the same functionaity in a simple:

s1.contains(" ");

and there's no use in saying "that wasn't there yet when I posted", since that reply is three years old.

malli: no doubt it is. my point was, it was redundant, for (at least) two reasons.

  1. the problem of the OP was solved 3 years ago
  2. there was a solution much shorter, easier and efficiƫnter compared to yours suggested by JamesCherrill. the line of code I wrote, is what he suggested. it replaces about 85% (if not more) of your code.
This article has been dead for over six months. Start a new discussion instead.