如何解决如何在 Java 中使用 indexOf 进行计数?
我想从 String 替换并打印它替换了多少次。
例如)
输入: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;
// *** 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
解决方法
只需使用要替换的字符串的长度增加循环的计数器变量即可。
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。