我正在尝试编写一个Java程序,该程序将字符串作为输入并计算字符串中字符的出现次数,然后打印一个新字符串,该字符串后跟出现次数。
例如
输入字符串:
aaaabb
输出字符串:
a4b2
输入字符串:
aaaaabbbc
输出字符串:
a5b3c1
我正在发布我的 java 代码。
它在投掷StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}