patternjavaModerate
Replace multiple occurrences of a character
Viewed 0 times
occurrencescharacterreplacemultiple
Problem
I try to replace multiple occurrences of a character with a single character.
Input:
hhiii!!! hooowww aaareee yyyooou???
Output:
hi! how are you?
Here I need review for
Input:
hhiii!!! hooowww aaareee yyyooou???
Output:
hi! how are you?
public class CharSingleOccurrence {
public static void main(String... args){
charSingleOccurrence("hhiii!!! hooowww aaareee yyyooou???");
}
public static void charSingleOccurrence(String str){
int i=0;
int j=0;
char arr[]=new char[50];
while (i<str.length()-1) {
if(str.charAt(i)!=str.charAt(i+1)){
arr[j]=str.charAt(i);
i++;
j++;
}else{
i++;
}
}
arr[j]=str.charAt(str.length()-1);
for(char c:arr){
System.out.print(c);
}
}
}Here I need review for
char arr[]=new char[50];
arr[j]=str.charAt(str.length()-1);
Solution
Maybe I am wrong but I prefers to use the
Here is my code,
regex for this kind of text manipulation.Here is my code,
System.out.println("hhiii!!! hooowww aaareee yyyooou???"
.replaceAll("(.)\\1+","$1"));Code Snippets
System.out.println("hhiii!!! hooowww aaareee yyyooou???"
.replaceAll("(.)\\1+","$1"));Context
StackExchange Code Review Q#5618, answer score: 11
Revisions (0)
No revisions yet.