java 在Java中查看字符串是否以空格开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4262621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
See if a string begins with whitespace in Java
提问by Daniel O'Connor
I know that trim removes whitespace from the beginning and end of a string, but I wanted to check if the first character of a string is a whitespace. I've tried what seems about everything, but I can't seem to get it to work.
我知道修剪会从字符串的开头和结尾删除空格,但我想检查字符串的第一个字符是否为空格。我已经尝试了所有看起来的东西,但我似乎无法让它发挥作用。
Can someone point me in the right direction? I'd appreciate it if regular expressions were not used.
有人可以指出我正确的方向吗?如果不使用正则表达式,我将不胜感激。
Thanks a lot!
非常感谢!
回答by casablanca
if (Character.isWhitespace(str.charAt(0))) {
// do something
}
回答by maerics
if (Character.isWhitespace(str.charAt(0))) //...
回答by digiarnie
public void yourMethod(String string) {
if (isLengthGreaterThanZero(string) && isFirstCharacterWhiteSpace(string)) {
...
}
}
private boolean isFirstCharacterWhiteSpace(String string) {
char firstCharacter = string.charAt(0);
return Character.isWhitespace(firstCharacter);
}
private boolean isLengthGreaterThanZero(String string) {
return string != null && string.length() > 0;
}
回答by sanssucre
"string".startsWith(" ")