[英]How to count white spaces in a given argument?
I find it strange why spaceCount doesn't add up when the expression is "12 + 1". 我觉得奇怪的是为什么当表达式为“12 + 1”时,spaceCount不会加起来。 I get an output 0 for spaceCount even though it should be 2. Any insight would be appreciated! 我得到了spaceCount的输出0,即使它应该是2.任何见解都将受到赞赏!
public int countSpaces(String expr) {
String tok = expr;
int spaceCount = 0;
String delimiters = "+-*/#! ";
StringTokenizer st = new StringTokenizer(expr, delimiters, true);
while (st.hasMoreTokens()) {
if ((tok = st.nextToken()).equals(" ")) {
spaceCount++;
}
}
return spaceCount; // the expression is: 12 + 1, so this should return 2, but it returns 0;
}
您的代码似乎没问题,但如果您想要计算空格,可以使用此代码:
int count = str.length() - str.replace(" ", "").length();
A tokenizer is overkill (and doesn't really help you) for this problem. 对于这个问题,一个标记器是过度的(并没有真正帮助你)。 Just loop through all the characters and count the spaces: 只需遍历所有字符并计算空格:
public int countSpaces( String expr )
{
int count = 0;
for( int i = 0; i < expr.length(); ++i )
{
if( expr.charAt(i) == ' ' )
++count;
}
return count;
}
另一个单行解决方案可能是以下,它也对字符串执行NULL检查。
int spacesCount = str == null ? 0 : str.length() - str.replace(" ", "").length();
Can also use: 也可以用:
String[] strArr = st.split(" ");
if (strArr.length > 1){
int countSpaces = strArr.length - 1;
}
This will find white spaces, including special ones. 这将找到白色空间,包括特殊空间。 You can keep the pattern so you don't need to compile it every time. 您可以保留模式,这样您就不必每次都编译它。 If just need to search for " ", a loop should do it instead. 如果只需要搜索“”,则循环应该代替。
Matcher spaces = Pattern.compile("\\\\s").matcher(argumentString); int count = 0; while (spaces.find()) { count++; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.