Skip to content

Instantly share code, notes, and snippets.

@reza-ryte-club
Created August 22, 2015 09:34
Show Gist options
  • Save reza-ryte-club/5dd7917d6b1a134500e2 to your computer and use it in GitHub Desktop.
Save reza-ryte-club/5dd7917d6b1a134500e2 to your computer and use it in GitHub Desktop.
Compress consecutive character occurrence of a character in a String
public class Compress {
public static String compressedString(String str){
StringBuilder dest = new StringBuilder();
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
dest.append(c);
int j = i;
int count =1 ;
if(i<str.length()-1)
if(j<str.length()-2){
while(c==str.charAt(j+1)){
count++;
j++;
i++;
}}
if(count>1)
dest.append(count);
}
return dest.toString();
}
public static void main(String[] args) {
String word = "Hello";
System.out.println(compressedString(word));
//Output should be like hel2o
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment