Reputation: 123
How can i check the white space at the beginning of the string.
Upvotes: 3
Views: 10513
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
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
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
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
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