java - 计算一个字符在字符串中以连续方式出现的次数
问题描述
我是 Java 新手。我正在尝试打印字符串中存在的字符及其计数。仅当旁边出现相同的字符时,计数才会增加。
前任:
输入/输出:Sssgs
输出/输出: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
解决方案
我刚刚对您的代码进行了一些更正,下面是它的样子:
public static void main(String[] args) {
String s = "Sssgs";
char[] ch = s.toCharArray();
int[] count = new int[20];
for(int i=0;i<ch.length;i++)
{
count[i]=0;
for(int j=i;j<ch.length;j++)
{
if(ch[i]==ch[j])
{
count[i]++;
} else {
break;
}
}
}
//Prints Distinct char
for(int i=0;i<ch.length;i += count[i])
{
System.out.print(ch[i] + "" +count[i]);
}
}
当我刚刚读取字符及其出现次数然后在迭代中跳跃该数字时,大多数变化都发生在 Prints Distincts 中。它让我停在下一个不同的角色上
“Sssgs”的输出是“S1s2g1s1”,“HelloWorld”的输出是“H1e1l2o1W1o1r1l1d1”
推荐阅读
- docker - 尝试在 docker 中更新 posgres 数据库导致机器拒绝连接
- android - Glide not Loading image from StorageReference
- ios - CarPlay 与 Apple 企业开发者计划
- ios - TextField 大小写验证
- oracle - oracle 表单未显示所有字段
- kubernetes - GKE:身份感知代理 > L7 负载均衡器 > 自定义主机和路径规则 > 错误代码 11
- c# - foreach 中的异步方法并将结果添加到列表中
- java - 如何在 Criteria API / JPQL 中使用具有一对多属性的 JPA 投影
- python-3.x - 我试图安装高速公路(0.14.1)。但它显示为''没有为高速公路找到匹配的分布== 0.14.1''
- node.js - google oauth 令牌如何用于在 Nodejs RESTapi 中为用户签名