忽略空格,只计算字母

时间:2018-07-24 07:20:50

标签: java

您能为我们的程序提供一个忽略空格的想法吗,只计算字母甚至是其他小巧的大写字母

public class evennumbersloop {

    public static void main(String[] args) {

        String str = "Hello World uuuu iii pppp jjj";

        int count = 0;

        for (int i = 0; i <= str.length() - 1; i++) {

            if (str.charAt(i) != ' ') {
                if (count % 2 == 0) {
                    String str1 = "";
                    str1 = str1 + str.charAt(count);
                    System.out.print(str1.toUpperCase());
                } else {
                    System.out.print(str.charAt(count));
                }

                count++;
            }
        }

    }
}

2 个答案:

答案 0 :(得分:0)

要仅计算字母,可以使用正则表达式并编写如下代码:

public static void main(String[] args) {
   Pattern pattern = Pattern.compile("\\p{Alpha}");
   Matcher matcher = pattern.matcher("Hello World uuuu iii pppp jjj");
   int count = 0;
   while (matcher.find())
       count++;
   System.out.println(count);
}

答案 1 :(得分:0)

所以你的意思是

String str = "Hello World uuuu iii pppp jjj";

忽略空格并计算出现的字母的数量->实际上没有空格的字符串的长度吗?

String str = "Hello World uuuu iii pppp jjj";
System.out.println("Length of string with spaces: "+str.length());
str = str.replaceAll("\\s", "");
System.out.println("Length of String without white spaces: "+str.length());

输出:

Length of string with spaces: 29
Length of String without white spaces: 24