desislava_topuzakova

06. Replace Repeating Chars

Nov 12th, 2021
1,805
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class ReplaceRepeatingChars {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         String input = scanner.nextLine().trim();
  7.  
  8.         StringBuilder sb = new StringBuilder();
  9.  
  10.         if (input == null || input.length() == 0) {
  11.             return;
  12.         }
  13.  
  14.         char previousChar = input.charAt(0);
  15.         sb.append(previousChar);
  16.  
  17.         for (int i = 1; i < input.length(); i++) {
  18.             char ch = input.charAt(i);
  19.             if (ch != previousChar) {
  20.                 sb.append(ch);
  21.                 previousChar = ch;
  22.             }
  23.         }
  24.  
  25.         System.out.println(sb);
  26.     }
  27. }
  28.  
Advertisement
Add Comment
Please, Sign In to add comment