java 使用 charAt() 查找空格、换行符和制表符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7815713/
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
Finding Spaces, Newlines and Tabs with charAt()
提问by bwoogie
I'm trying to check if there is a space, a newline or a tab at the current character location. Spaces work but tabs and newlines dont. Go figure, I'm using escapes for those, and just a regular space for a space... What's the correct way to find these at a location?
我正在尝试检查当前字符位置是否有空格、换行符或制表符。空格有效,但制表符和换行符无效。想想看,我正在为这些使用转义符,并且只是一个常规空间作为一个空间......在某个位置找到这些的正确方法是什么?
if(String.valueOf(txt.charAt(strt)).equals(" ") ||
txt.charAt(strt) == '\r' ||
txt.charAt(strt) == '\n' ||
txt.charAt(strt) == '\t') {
//do stuff
}
回答by Amadan
This works for me:
这对我有用:
char c = txt.charAt(strt);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
System.out.println("Found one at " + strt);
Yours works too, although it's a bit harder to follow. Why it doesn't work for you I don't know - maybe the string is badly formed? Are you sure you actually have tabs and stuff in it?
你的也有效,虽然它有点难以遵循。我不知道为什么它对你不起作用 - 也许字符串形成不良?你确定你真的有标签和东西吗?
回答by Saurabh Saxena
It should work just fine, check your input string. Also, the space can be checked by comparing a blank space character. Creating a new String object just for comparison is costly.
它应该可以正常工作,请检查您的输入字符串。此外,可以通过比较空格字符来检查空格。创建一个仅用于比较的新 String 对象的成本很高。
回答by Brian Roach
Looking at the docs for Editable
in android, it returns a char
. Therefore ...
查看Editable
android中的文档,它返回一个char
. 所以 ...
if (txt.charAt(strt) == ' ' ||
txt.charAt(strt) == '\r' ||
txt.charAt(strt) == '\n' ||
txt.charAt(strt) == '\t')
{
//do stuff
}
Will produce the expected result.
将产生预期的结果。
回答by hyhashemi
This regex [\s] will do the work. It matches the whitespace, Equivalent to [\t\n\r\f].
这个正则表达式 [\s] 将完成这项工作。它匹配空格,相当于 [\t\n\r\f]。