0

Given String str1- "happy sunday", and String str2- "sun", how can I return a string that replaces all characters in str1 with 'X' except for the occurrences of the substring s2?

So the output return value in this case should be the string - "XXXXXXsunXXX".

Note I'm not trying to print this string, but return it to a method. The method has two string parameters- str1 and str2, and has a string return value which is in this case - XXXXXXsunXXX.

This is what I have so far.. The problem is I don't know how to identify at which index str2 is occuring in str1! Once I know at which index the substring starts and ends, I can just concatenate the X signs with the substring.

public String blah(String str1, String str2) 
{
    int length = str1.length()-1;

    String z = "";

    if(!str1.contains(str2))
    {
        for(int i = 0; i <= length; i++)
        {
            z+= 'X';
        }
        return z;
    }
    else
    {
      ...
    }
}
Jason
  • 11,744
  • 3
  • 42
  • 46
Milos.l
  • 41
  • 7
  • Those aren't duplicates of this question. This question is looking for specific patterns to keep - not just characters. – Jason Oct 30 '17 at 05:09

1 Answers1

0

You can use str1.indexOf(str2); to find the first occurrence of str2 in str1. The return value is an index into str1 or -1 if str2 was not found. Then use str1.indexOf(str2, lastIndex+str2.length) to find a second occurrence and so forth.

Jochen Bedersdorfer
  • 4,093
  • 24
  • 26