我在完成这段代码时遇到了一些困难。基本上,我必须计算一个字母在给定字符串中出现的次数。例如,ABA应输出以下内容
"A appears 1 times"
"B Appears 1 times"
"A Appears 1 times"
但是,我编写的以下代码执行以下操作(它是方法的一部分)
public static char[] counter(char[] original, char[] manipulated) {
int counter =0;
for (int i=0; i<manipulated.length; i++) {
for (int j=0; j<original.length; j++) {
if (original[j] == manipulated[i]) {
counter++;
} else {
}
}
System.out.println(manipulated[i] + " appears " + counter + " times");
counter = 0;
}
return manipulated;
}
输出是这样的:
"A appears 2 times"
"B appears 1 times"
"A appears 2 times"
哪个没错,但这不是我想要的。那么请你尽快帮我解决这个问题。我知道我想重置一些变量,但我不知道在哪里重置它。 提前致谢。
*一些说明: 被操纵的变量只是不包含重复的字符串 原来是abaa和操纵将是aba :))
答案 0 :(得分:2)
如果你的预期行为只是&#34;打印出每个角色出现在一行中的次数&#34;那么我不确定你为什么需要manipulated
变量。您当前的代码只接受它作为参数,然后将其保持不变。
因此,除非我误解了这个问题,否则它可能是一个更为简单的问题:
void showConsecutiveCharacterCounts(char[] input) {
int consecutiveCount = 0;
/* iterate through all chars */
for (int i = 0; i < input.length; i++) {
/* increment count - will be 1 first time */
consecutiveCount++;
/* if we are at the end of a sequence of chars
I.e. end of input OR next char does not match */
if (i == input.length - 1 || input[i] != input[i + 1]) {
/* print previous sequence */
System.out.println(input[i] + " appears " + consecutiveCount + " times");
/* and reset count */
consecutiveCount = 0;
}
}
}
答案 1 :(得分:1)
如果您想知道同一个字符连续出现的次数,可以将代码更改为
public static void main(String[] args) {
System.out.println(counter("AAACCAAAAAAAB"));
}
public static String counter(String s) {
int counter = 0;
int j;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
j = i;
char c = s.charAt(i);
for (; j < s.length(); j++) {
if (counter == 0) {
sb.append(c);
}
if (c == s.charAt(j)) {
counter++;
} else {
break;
}
}
System.out.println(s.charAt(i) + " appears " + counter + " times");
counter = 0;
i = j;
}
return sb.toString();
}
UPDATE 更改了代码,因此您无需提供两个char [] - 现在您输入任何字符串,如&#34; AAACCAAAAAAAB&#34; (aka&#39; original&#39;)和char []以前被称为&#39;操纵&#39;将由该方法返回。
结果:
A appears 3 times
C appears 2 times
A appears 7 times
B appears 1 times
ACAB