简体   繁体   English

如何检查字符串开头的空格?

[英]How to check space at the beginning of the string?

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

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

you can try myString.startswith(" ") 你可以尝试myString.startswith(" ")

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

...and to remove bordering white spaces from each side: myString.trim() ...并从每一侧删除边界空白: myString.trim()

To check the first character is whitepace: 要检查第一个字符是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: 编辑:不要忘记首先检查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. 说明: trim将删除前导和尾随空格。 If the string exists and is not empty, then we create a new string from the first char and trim it. 如果字符串存在且不为空,那么我们从第一个char创建一个新字符串并修剪它。 Now, if the result is empty, the the original string did start with a white space and we return true. 现在,如果结果是空的,原来的串启动一个空白,我们返回true。 Otherwise, the answer is "false". 否则,答案是“假的”。

Note - this solution can't compete with Richard H's , which is more elegant ;) 注意 - 这个解决方案无法与Richard H's竞争,后者更优雅;)

it is simple just see http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim() 这很简单,请看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. trim()方法通过检查unicode值'\\ u0020'(空间值)修剪字符串开始和结束时的空间(unicode中的大多数最小值是'\\ u0020'=空格)所以它检查从开始到获取值的每个索引大于空间unicode并且从最后检查直到它获得大于空间的值并且修剪开始和结束。 finally return substring without space at start and end. 最后在开始和结束时返回没有空格的子字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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