I have String set which is "5X3I3M3X"
I want to separate 5X = 1X1X1X1X1X , depends on number in front of character "X"
So finally it could be 1X1X1X1X1X3I3M1X1X1X
I did it like below,
String str = "5X3I3M3X";
StringBuffer sBuffer = new StringBuffer("");
for(int i = 1 ; i < str.length() ; i=i+2) {
if( str.charAt(i) == 'X'){
if(str.charAt(i-1) == 1){
sBuffer.append(str.charAt(i-1)+""+str.charAt(i));
}else{
StringBuffer sBufferTemp = new StringBuffer("");
for(int j=0 ; j < Character.getNumericValue(str.charAt(i-1)) ; j++){
sBufferTemp.append("1X");
}
sBuffer.append(sBufferTemp.toString());
}
} else {
sBuffer.append(str.charAt(i-1)+""+str.charAt(i));
}
}
System.out.println(sBuffer.toString());
And I want to know is there any simple way to separate that logic? note. If I want to add to separate 'I', then it should be dynamically change also like "1X1X1X1X1X1I1I1I3M1X1X1X"
I can change it my code extpend if (str.charAt(I) == 'I') ....
I hope there is another simple way to implement this.
Aucun commentaire:
Enregistrer un commentaire