我正在尝试计算一个字符在字符串中连续出现的次数。似乎无法用这个去任何地方:\ 如果您能帮助我,我将非常感激。
提前致谢:)
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/