【发布时间】:2023-03-04 22:18:02
【问题描述】:
我是 Java 新手。我正在尝试打印字符串中存在的字符及其计数。只有当旁边出现相同的字符时,计数才会增加。
例如:
I/O : Sssgs
O/P : S1s2g1s1
计算每个字符的出现次数会给出完整计数的计数,而不管字符是否彼此相邻。篡改 i & j 循环会导致 OutOfBounds 错误。
//ch[] is the String converted to a character array.
//count[] is an array to store count of the characters
//Checks if present char and next char are same and increments count
for(int i=0;i<ch.length;i++)
{
count[i]=0;
for(int j=0;j<ch.length;j++)
{
if(ch[i]==ch[j])
{
count[i]++;
}
}
}
//Prints Distinct char
for(int i=0;i<ch.length;i++)
{
int j;
for(j=0;j<i;j++)
{
if(ch[i]==ch[j])
{
break;
}
}
if(i==j)
{
System.out.print(ch[i]+" "+count[i]);
}
}
输入是 > HelloWorld
预期的输出应该是 > H1 e1 l2 o1 W1 o1 r1 l1 d1
【问题讨论】:
-
我会使用
StringBuiler。 1)遍历字符串,2)将字符添加到构建器并增加计数器 3.a)如果前一个字符等于当前字符,则增加计数器,3.b)如果不相等,附加计数器并重置它 -> 在 2 处继续。 -
重新开始,用纸和笔“编程”。只需要知道前面的字符(char)和它出现了多少次(int),不是吗?或当前字符 (char) 以及它跟随的次数 (int)。解决方案很短。
-
您的意思是“连续”(彼此相邻)吗? “传染性”意味着可能会传播,就像疾病一样。
-
请阅读“如何创建minimal reproducible example”。然后使用edit 链接改进您的问题(不要通过 cmets 添加更多信息)。否则我们无法回答您的问题并为您提供帮助。你给出了预期的输出,省略了实际的输出。当你有异常时,包括异常堆栈跟踪。