John D
John D

Reputation: 123

How to check space at the beginning of the string?

How can i check the white space at the beginning of the string.

Upvotes: 3

Views: 10513

Answers (5)

prasad
prasad

Reputation: 1

it is simple just see http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim()

trim() method trim space at starting and ending of a string by check unicode value '\u0020' (value of space)(most minimum value in unicode is '\u0020' = space) so it check every index from starting until get value greater than space unicode and also check from last until it get value greater than space and trim start & end. finally return substring without space at start and end.

Upvotes: -1

dagnelies
dagnelies

Reputation: 5321

http://download.oracle.com/javase/6/docs/api/java/lang/String.html

you can try myString.startswith(" ")

or myString.matches("^ +.*")

...and to remove bordering white spaces from each side: myString.trim()

Upvotes: 11

Andreas Dolk
Andreas Dolk

Reputation: 114767

Just to add one more...

public static boolean isStartingWithWhitespace(String str) {
   if (str == null || str.isEmpty())
      return false;

   return str.substring(0,1).trim().isEmpty();
}

Explanation: trim will remove leading and trailing white spaces. If the string exists and is not empty, then we create a new string from the first char and trim it. Now, if the result is empty, the the original string did start with a white space and we return true. Otherwise, the answer is "false".

Note - this solution can't compete with Richard H's, which is more elegant ;)

Upvotes: 1

Richard H
Richard H

Reputation: 39055

To check the first character is whitepace:

Character.isWhitespace(myString.charAt(0))

Or use a regex:

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

Edit: Don't forget to check for null or zero-length strings first:

if (myString != null && myString.length() > 0) {
  ....  
}

Upvotes: 6

subodh
subodh

Reputation: 6158

String str=" hi";
    if(str.startsWith(""))
    {
        System.out.println("Space available");
    }else{
        System.out.println("NO Space available");
    }

You can achieve it through different ways also. various way available to achieve this.

Upvotes: 1

Related Questions