我想要计算字符串中非空白字符的数量。使用字符串方法来计数字符
当没有前导空格时它工作正常,但当我从中添加3个空格时,它会使非空白字符的数量加倍。
这是我的代码:
import java.io.*;
import java.util.*;
public class countCharacters
{
public static void main(String[] args) throws Exception
{
String str1;
int count;
count = 0;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
while(str1.length() > 0)
{
System.out.println("The String ''" + str1 + "''");
System.out.println("has " + str1.length() + " Characters, including all blanks.");
for(int i=0; i < str1.length(); ++i)
if(str1.charAt(i) !=' ')
count++;
str1 = str1.trim();
System.out.println("and " + str1.length() + " Characters, trimmed of leading and trailing blanks.");
System.out.println("and " + count + " non-blank characters.");
System.out.println("");
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
}
System.out.println("Program complete.");
}
}
相信我 - 格式化您的代码将有助于您在调试过程中很多。如果你看不懂它,你怎么能检查你的代码!如果您使用的是Eclipse,请按Ctrl + Shift + f,并且您的代码将自动生成。在这一点上我真的不能看你的代码,因为它对我来说是不可读的。 – 2014-11-04 18:30:09
如果在**数字之前修剪**,会不会更好? – 2014-11-04 18:30:55
@MatiCicero他/她只是在执行'trim'以输出字符串的修剪长度。这些角色已经被计算在内。无论它们是在“trim”之前还是之后都被计算在内。 – 2014-11-04 18:31:31