如何计算java字符串中的空格? [英] how to count the spaces in a java string?
本文介绍了如何计算java字符串中的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算字符串中的空格数,但是当我运行它时,我的代码给了我一个错误的数字,出了什么问题?
I need to count the number of spaces in my string but my code gives me a wrong number when i run it, what is wrong?
int count=0;
String arr[]=s.split("\t");
OOPHelper.println("Number of spaces are: "+arr.length);
count++;
推荐答案
s.length() - s.replaceAll(,)。length()
返回空格数。
还有更多方法。例如
int spaceCount = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
等等。
在您的情况下,您尝试使用 \t
- 选项卡。如果您使用,您将获得正确的结果。使用
\s
可能会造成混淆它匹配所有 whitepsaces - 常规空格和TAB。
In your case you tried to split string using \t
- TAB. You will get right result if you use " "
instead. Using \s
may be confusing since it matches all whitepsaces - regular spaces and TABs.
这篇关于如何计算java字符串中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文