Program opened below. You can scroll through the algorithm, Java code and output.

Remove Consecutive Repeated Characters

Download .java

Question

Read a word and replace every run of repeated consecutive characters with a single occurrence.

Step 1: Start and create a Scanner. Step 2: Accept the input word. Step 3: Initialize an empty result string. Step 4: Set the character position to zero. Step 5: Run a loop until the last character has been examined. Step 6: Read the character at the current position. Step 7: If it is the first character, add it to the result. Step 8: Otherwise compare it with the immediately preceding character. Step 9: If the two characters are different, add the current character to the result. Step 10: If the characters are the same, do not add anything. Step 11: Advance to the next character. Step 12: Repeat the comparison for the entire word. Step 13: Display the result containing one character per consecutive run. Step 14: Stop.
Java
import java.util.*;
class RemoveRuns {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String word = sc.next();
        String result = "";
        for (int i = 0; i < word.length(); i++) {
            if (i == 0 || word.charAt(i) != word.charAt(i - 1)) {
                result += word.charAt(i);
            }
        }
        System.out.println(result);
    }
}
Input: Piiiiiccckk Output: Pick
← Previous Program 6 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.