tags:

views:

88

answers:

3

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

A: 

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();
}

Sample usage

public static void main(String[] args) {
    String i = "Hello how Hello are Hello";
    System.out.println(transform(i));
}
dfa
I was actually wanting something different ...i am sorry to put up the question incorrectlyi want it something like this "Hello1ok how Hello2ok are Hello3ok"plz help
Your testcase doesn't test anything. How do you know the tested function works?
Hi i am using JDK 1.3 so it doesn't support "String.format" Plz suggest
@Gourav: so you must use `StringBuffer`, not `StringBuilder` and do something like in place of `String.format`: `stringBuffer.append(s).append(' ').append(String.valueOf(i++))`;
dfa
+1  A: 

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;
    }

}
Matt
Some people, when confronted with a problem, think "I know, I'll use recursion." Now they have two problems. :D
Vineet Reynolds
Yeah something like that :)
Matt
The "contains()" method on string is giving compilation errors.Plz Help..!!
You didn't note that you were using 1.3 before, it is a prety important detail. Just switch the if to "output.indexof(HELLO) != -1"
Matt
A: 

Use regular expressions. Here is how

Nir
I don't know regex is one of those things that always seems like an answer to string manipulation. Then I look at the solution....
Matt