Reputation: 25
How could I find a letter in string (if it's "cc" together it leaves it, but if it's only one "c" it deletes it)?
I have no idea how to do it, so if someone knows I would be really thankful.
I tried splitting whole string into a tab, and checking if index is "c" and then looking +-1 index, to check if "c" is next to it but it didn't work.
Now i changed "==" but it still misses some letters. if i input "abaabbcbaccb" it should output →"aabaaaabbaaccb" My program misses that standalone "c"..
public class NovNiz{
public static String urejanjeBesedila(String a){
String niz="";
a.toLowerCase();
String spr = a.replaceAll("a", "aa");
spr = spr.toLowerCase();
spr = spr.replaceAll("bb", "b");
String []tab=spr.split(" ");
if(tab.length>0){
for(int i=0;i<tab.length;i++){
if(tab[i].indexOf("cc")>0){
niz=niz+tab[i]+" ";
continue;
}
if(tab[i].indexOf("c")>=0){
int x=tab[i].indexOf("c");
StringBuffer sb= new StringBuffer(tab[i]);
sb.deleteCharAt(x);
tab[i]=sb.toString();
}
niz=niz+tab[i]+" ";
}
}
else{
String []tab2=spr.split("");
for(int i=0;i<tab.length;i++){
if(i==0){
if("c".equals(tab[i])&&"c".equals(tab[i+1])){
}
else if("c".equals(tab[i])){
tab[i]="";
}
}
else{
if("c".equals(tab[i])&&"c".equals(tab[i+1])||"c".equals(tab[i-1])){
}
else if("c".equals(tab[i])){
tab[i]="";
}
}
}
}
return niz;
}
}
Upvotes: 0
Views: 159
Reputation: 2968
You can just do:
final String input = "I'm a test string to drop 'c' but not 'cc', 'ccc', 'cccc', ok ?";
String result = input
.replaceAll( "c([^c])", "$1" )
.replaceAll( "c([^c])", "cc$1" );
// result will be "I'm a test string to drop '' but not 'cc', 'ccc', 'cccc', ok ?"
Upvotes: 1