0

I have a String as follows

String str=" Hello World, Hello World, Hello";

I want to replace third "Hello" to "Hi" In Java. Is there any way that I can touch only the part I need in a String ?

2 Answers2

1

Your logic is not totally explicit, but anyway I think the best is to use Pattern. Take a look at this tutorial.

LexLythius
  • 1,904
  • 1
  • 12
  • 20
0

Here's a method that will return the index of the nth occurrence of a string in another string:

/**
 *  Returns the index of the nth occurrence of needle in haystack.
 *  Returns -1 if less than n occurrences of needle occur in haystack.
 */
public int findOccurrence(String haystack, String needle, int n) {
    if (n < 1) {
        throw new IllegalArgumentException("silly rabbit...");
    }
    int count = 0;
    int len = needle.length();    
    int idx = haystack.indexOf(needle);
    while (idx != -1 && ++count < n) {
        idx = haystack.indexOf(needle, idx + len);
    }
    return idx;
}

The rest should be trivial to implement....

jahroy
  • 22,322
  • 9
  • 59
  • 108