java—计算字符串中以大写字母开头的所有单词

ef1yzkbh  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(456)

我在大学学习java,需要编写一个静态int countcapitals(string s)方法,返回字符串中以大写字母开头的单词数。
大写字母是大写字母类型或标题大写字母类型的字符。单词是由一个或多个空格、字符、符号或标点符号分隔的字母或数字序列。
新的。你好,我亲爱的朋友们!这里的单词以ć资本ł字母“)==6
我只允许在字符串和字符类中使用方法

public class New {
    static int countCapitals(String s) {
        int c = 0;
        if (Character.isUpperCase(s.charAt(0)) == true
                || Character.isTitleCase(s.charAt(0)) == true) {
            c++;
        }
        for (int i = 0; i < s.length() - 1; i++) {
            if (Character.isLetter(s.charAt(i)) == false
                    && Character.isLetter(s.charAt(i + 1)) == true) {
                if (Character.isUpperCase(s.charAt(i + 1)) == true
                        || Character.isTitleCase(s.charAt(i + 1)) == true) {
                    c++;
                }
            }
        }
        return c;
    }
}

这是我的代码,但在某些测试中不起作用。测试已经结束了,所以我不知道是哪个。你能告诉我哪里出了问题,怎么解决吗?

nnvyjq4y

nnvyjq4y1#

java的内置regex包就是我的方式:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordsStartingWithCapitalLetter {

    public static void main(String[] args) {
        // Test 1 -- simple sentence
        String s = "The Quick Brown Fox jumps over the lazy Dog";
        System.out.println("\ninput string: " + s);
        System.out.println("capitalized words:" + getCountOfWordsWithInitialCap(s));

        // Test 2 -- punctuation and newlines
        s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\n"
        + "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation\n"
        + "ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit\n"
        + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat\n"
        + "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
        System.out.println("\ninput string: " + s);
        System.out.println("capitalized words:" + getCountOfWordsWithInitialCap(s));

        // Test 3 -- Scottish sirnames and hyphens
        s = "The quick brown MacGavin jumps over the lazy MacGowan-dog";
        System.out.println("\ninput string: " + s);
        System.out.println("capitalized words:" + getCountOfWordsWithInitialCap(s));
    }

    private static final Pattern WORD_WITH_CAP_REGEX = Pattern.compile("([A-Z][-A-Za-z]*)");

    private static int getCountOfWordsWithInitialCap(String s) {
         int count = 0;
         Matcher matcher = WORD_WITH_CAP_REGEX.matcher(s);
         while(matcher.find()) {
            count++;
            String capitalizedWord = matcher.group(1);
            System.out.println("\t"+count+" : "+capitalizedWord);   // remove if you don't want to see the matches
         }
         return count;
    }
}

相关问题