java - 检查一个字符在字符串中连续出现了多少次

标签 java string loops

我正在尝试计算一个字符在字符串中连续出现的次数。似乎无法用这个去任何地方:\ 如果您能帮助我,我将非常感激。

提前致谢:)

        int totCharacters=0, vowels=0, digits=0, odds=0, consecutive=0, index=0;
        String text;
        char ch;

        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a sentence terminated with a full stop or exclamation mark: ");
        text = input.nextLine();

        do {
            ch = text.charAt(index);

            if(ch=='.' && ch=='!')
                break;

            if(index<text.length()-1)
                totCharacters++;
            if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
                vowels++;
            if(ch>='0' && ch<='9')
                digits++;
            if(ch=='1' || ch=='3' || ch=='5' || ch=='7' || ch=='9')
                odds++;

            index++;

        }while(ch!= '.' && ch!='!');

        for(int i=0; i<text.length(); i++)
        {

            if(ch==text.charAt(i))
                consecutive++;

        }

最佳答案

这将计算所有连续的字符(我相信,无法编译 atm)。这可能不是您想要的。我可以根据你所说的连续字符的含义进行修改。全部连续?连续最高?

我将 for 循环移至 do while 内,以便您对每个字符执行此操作。我还将 int i 变量基于索引,这样您就不会查看当前正在检查的字符之前的字符。还将索引的递增移至 for 循环之后,以便将其自身视为一个连续的,因此“AA”将是 2 个连续的。

我需要你定义连续应该等于什么才能正确计算。现在,它将查看每个字符,并为每个匹配字符(包括其自身)连续添加 1。

    int totCharacters=0, vowels=0, digits=0, odds=0, consecutive=0, index=0;
    String text;
    char ch;

    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a sentence terminated with a full stop or exclamation mark: ");
    text = input.nextLine();

    do {
        ch = text.charAt(index);

        if(ch=='.' && ch=='!')
            break;

        if(index<text.length()-1)
            totCharacters++;
        if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
            vowels++;
        if(ch>='0' && ch<='9')
            digits++;
        if(ch=='1' || ch=='3' || ch=='5' || ch=='7' || ch=='9')
            odds++;


    for(int i=index; i<text.length(); i++)
        {

             if(ch==text.charAt(i))
             {
                consecutive++;
             }
             else 
             {
                 break;
             }

        }
        index++;
        }while(ch!= '.' && ch!='!');

关于java - 检查一个字符在字符串中连续出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20335852/

相关文章:

java - Btrace 不返回任何东西

C# 编辑动态字符串

list - clojure 尾递归中的 java.lang.StackOverflowError

javascript - 从javascript中括号之间的多个数组循环

java - 更新包含列表的数据时,restTemplate.put 给出 "Can not deserialize instance of java.util.ArrayList out of START_OBJECT"

java - Opencv相机错误 - 初始化期间绿色闪烁

java - 有什么办法可以让下面的Java代码执行得更快吗?

java - 在 Java 中如何检查我是否已到达 String 的末尾?

Python从具有重复键的列表创建嵌套字典

java - java中Do/While循环的问题