I have a string like "Hello how Hello are Hello" I want to replace the number of times "Hello" occurs in the above string by an autoincrementing number.
Like "1 how 2 are 3"
"Hello" can occur any number of times
I have a string like "Hello how Hello are Hello" I want to replace the number of times "Hello" occurs in the above string by an autoincrementing number.
Like "1 how 2 are 3"
"Hello" can occur any number of times
try this simple method:
public static String transform(String input) {
StringBuilder stringBuilder = new StringBuilder();
int i = 1;
for (String s : input.split("Hello")) {
stringBuilder.append(String.format("%s %d", s, i++));
}
return stringBuilder.toString();
}
public static void main(String[] args) {
String i = "Hello how Hello are Hello";
System.out.println(transform(i));
}
I don't know felt the need to do it with recursion.
public class StringReplacement {
private static final String HELLO = "Hello";
/**
* @param args
*/
public static void main(String[] args) {
String stringToTransform = "Hello how Hello are Hello";
System.out.println(transform(stringToTransform));
}
private static String transform(String stringToTransform) {
return transform(stringToTransform, 1);
}
private static String transform(String stringToTransform, int counter) {
String output = stringToTransform.replaceFirst(HELLO, String
.valueOf(counter));
if (output.contains(HELLO))
return transform(output, ++counter);
else
return output;
}
}