0

I need the program to return a message if the user input a string with blank spaces. for example "this is my house" is not allowed, "thisismyhouse" is allowed. right now I use this code to check for blank spaces

    for(int i = 0; i < blabla.length(); i++) {
        if (blabla.charAt(i) == ' ')
            flag++;
        }
    }
    if (flag != 0) {
        System.out.println("input must not contain spaces");
    }

I wonder if there's a built in function like 'blabla.equals' etc for this purpose? or a better way to write this?

2
  • 3
    how about using String.contains ? Commented Jun 9, 2014 at 8:37
  • blablabla.contains(" ") Commented Jun 9, 2014 at 8:38

4 Answers 4

1

Solution 1:

if(input.contains(" "))
   System.out.println("input must not contain spaces");

Solution 2:

if(input.indexOf(" ")>=0)
   System.out.println("input must not contain spaces");  

Solution 3:

You can simply allow the user to enter spaces and remove them yourselves instead:

 input = input.replaceAll(" ","");
Sign up to request clarification or add additional context in comments.

Comments

0

try

   if (blabla != null && blabla.contains (" ")) {
      System.out.println("input must not contain spaces");
      return;
   } 

Comments

0

this should do the trick.

if(blabla.contains(" ")){};

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

Comments

0

A little search would give you the answer but... There is a method defined in String that returns a boolean value for that purpose already.

if (blabla.contains(" ")) {
System.out.println("input must not contain spaces");
}

You can review the methods of String...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.