Skip to content
Advertisement

Code that takes a string and recognizes the number of consecutive letters

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 1 input:

JavaScript

Example 1 output:

JavaScript

Example 2 input:

JavaScript

Example 2 output:

JavaScript
JavaScript

Advertisement

Answer

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.
JavaScript

prints

JavaScript

In a comment (now deleted) you had enquired how to reverse the process. This is one way to do it.

  • allocate a StringBuilder to hold the result.
  • initialize count and currentChar
  • as the string is processed,
    • save a character to currentChar
    • then while the next char(s) is a digit, build the count
  • if the count is still 0, then the next character was a digit so bump count by one and copy the currentChar to the buffer
  • otherwise, use the computed length.
JavaScript

prints

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement