【问题标题】:How can I count with indexOf in Java?如何在 Java 中使用 indexOf 计数?
【发布时间】:2021-03-02 10:57:11
【问题描述】:

我想从字符串中替换并打印它替换了多少次。

例如)
输入 : aabba
来自:aa
到 : bb
ddbba
替换:1

输入:AAccaabbaaaaatt
来自:aa
到 : bb
ddccddbbddddatt
替换:4

我这里有个问题:

for (int i = 0; i < input.length(); i++) {
        if (inputL.indexOf(curStrL, i) > -1) {
            cnt++;
            i = (inputL.indexOf(curStrL, i))+1; // this part!
        } else
            continue; 
    } // for

我的老师说只使用 .indexOf.replace.toLowerCase

她举了一些例子,他们总是把两个字母替换成两个字母。 这就是为什么我输入“+1”来查找另一封信的原因。 如果我删除那个'+1',它会计算'aaa'两次。(aa a和aaa。它替换为'dda',所以这是错误的。) 但是这次我只替换一个字母(例如a)时,它计数的数字比实际需要的要少。(例如'aaa'只计数两次。)

有了老师的例子,效果很好,因为它们都替换了两个字母。 但我想改进这一点。

这是我所有的代码:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    while (true) {
        System.out.print("Input : ");
        String input = scan.next();
        System.out.print("from : ");
        String curStr = scan.next();
        System.out.print("to : ");
        String chStr = scan.next();

        String inputL = input.toLowerCase();
        String curStrL = curStr.toLowerCase();
        String chStrL = chStr.toLowerCase();

        String output = inputL.replace(curStrL, chStrL);

        int cnt = 0;
        if (inputL.indexOf(curStrL) == -1) {
            System.out.println("Do it again");
        } else
            System.out.println(output);

    for (int i = 0; i < input.length(); i++) {
        if (inputL.indexOf(curStrL, i) > -1) {
            cnt++;
            i = (inputL.indexOf(curStrL, i))+1; 
            // *** to make the code find from the next letter! ***
        } else
            continue; 
    } // for

        if (cnt > 0)
            System.out.println("replaced : " + cnt);
        else
            {System.out.println("can't replace. Do it again");
            break;}

        System.out.println("----------------");

    } // while
} // main

【问题讨论】:

    标签: java for-loop if-statement indexof


    【解决方案1】:

    只需将循环的计数器变量与要替换的字符串的长度一起增加即可。

    for (int i = 0; i < input.length(); i++) {
                if (inputL.indexOf(curStrL, i) > -1) {
                    cnt++;
                    i = (inputL.indexOf(curStrL, i));  // EDIT by Shraft
                    i = i + curStr.length() - 1;       // EDIT
                    // *** to make the code find from the next letter! ***
                } else
                    continue; 
            } // for
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 2012-05-26
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多