Predator44 Predator44 - 2 months ago 6
Java Question

Remove repeated characters in a string

I need to write a static method that takes a

String
as a parameter and returns a new
String
obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a
String
, it returns "make".
I already tried the following code, but it doesn't seem to display the last character.
Here's my code:

import java.util.Scanner;
public class undouble {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("enter String: ");
String str = console.nextLine();
System.out.println(removeSpaces(str));
}
public static String removeSpaces(String str){
String ourString="";
int j = 0;
for (int i=0; i<str.length()-1 ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}

}

return ourString;
}
}

Answer

The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:

EDIT:

public  void removeSpaces(String str){
        String ourString="";
        for (int i=0; i<str.length()-1 ; i++){
            if(i==0){
                ourString = ""+str.charAt(i);
            }else{
                if(str.charAt(i-1) != str.charAt(i)){
                    ourString = ourString +str.charAt(i);
                }
            }           
        }
        System.out.println(ourString);
    }