Issue
To do my job, I need a code that takes a word from the user, then recognizes the number of consecutive letters and outputs it in such a way that it prints the letter and the number of times it is repeated.
Example
input:
hhhttrew
output:
h3t2rew
input:
uuuuuuhhhaaajqqq
output:
u6h3a3jq3
I know it is very incomplete (:
String text = sc.nextLine();
int len = text.length();
int repeat = 0;
char[] chars = new char[len];
// To convert string to char
for (int h = 0; h < len; h++)
{
chars[h] = text.charAt(h);
}
String finaly = "";
for (char ignored : chars)
{
for (int j = 0 ; j <len ; j++ )
{
if (chars[j] == chars[j+1])
{
finaly = String.valueOf(chars[j]);
repeat++;
finaly = String.valueOf(repeat);
}
else
{
j++;
}
}
}
System.out.println(finaly);
Solution
Here is one way. You only need a single loop. The inner loop does the work. The outer loop simply supplies test cases.
- assign the first character
- and set count to 1 for that character
- then iterate until adjacent characters are different
- append count if > 1 and append the different character
- set count to 0 for next run.
String[] data = { "uuuuuuhhhaaajqqq",
"hhhttrew","abbcccddddeeeeeffffffggggggg" };
for (String s : data) {
String result = "" + s.charAt(0);
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) != s.charAt(i)) {
result += count <= 1 ? "" : count;
result += s.charAt(i);
count = 0;
}
count++;
if (i == s.length() - 1) {
result += count <= 1 ? "" : count;
}
}
System.out.printf("%-15s <-- %s%n", result, s);
}
prints
u6h3a3jq3 <-- uuuuuuhhhaaajqqq
h3t2rew <-- hhhttrew
ab2c3d4e5f6g7 <-- abbcccddddeeeeeffffffggggggg
Answered By – WJS
Answer Checked By – Mary Flores (BugsFixing Volunteer)