简体   繁体   中英

How to check space at the beginning of the string?

如何检查字符串开头的空白区域。

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()

To check the first character is whitepace:

Character.isWhitespace(myString.charAt(0))

Or use a regex:

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

Don't forget to check for null or zero-length strings first: 不要忘记首先检查null或零长度字符串:

if (myString != null && myString.length() > 0) {
  ....  
}
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.

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 ;)

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 '\ ' (value of space)(most minimum value in unicode is '\ ' = 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM