Remove repeated characters in a string
52,608
Solution 1
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);
}
Solution 2
You could use regular expressions for that.
For instance:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));
Output:
done
Pattern explanation:
"(.)\\1{1,}"
means any character (added to group 1) followed by itself at least once"$1"
references contents of group 1
Solution 3
maybe:
for (int i=1; i<str.length() ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
Author by
abedzantout
Updated on July 24, 2022Comments
-
abedzantout almost 2 years
I need to write a static method that takes a
String
as a parameter and returns a newString
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 aString
, 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; } }