这是我的简单代码。
导入java.util.Scanner;
public class WordLines
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
如果我要输入一个句子,例如“早安世界!” (此行17个非空白字符)
我怎样才能显示我的文本并在上面打印出非空白字符的数量。
最佳答案
使用正则表达式删除所有空格(空格、换行符、制表符),然后简单地获取字符串长度。
input.replaceAll("\\s+", "").length()
关于java - 读取字符串中非空白字符的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953588/