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


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

Recommended Answers

All 6 Replies

How about the "contains" method in the String class - or is that too obvious?

I solved the problem by using the regex "\\w+".

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("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.

Hi ,

No .

It is my own code.

Malli C.

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.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.