Coding Challenge Day-25: Problem 1: Replace nth occurance of a substring in a String

Hello! So I’m doing a 100 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 25: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: Replace nth occurance of a substring in a String

Sample input: String= “A cat ate late”
replace 1st occrance of “at” with “rane”
Output: A crane ate late

Solution:

``````package string;

public class Program015replace_substring {

static String currentPhrase="A cat ate late";

public static int findNthOccurance (String str, int n){
int a=0;

for(int i=0; i<currentPhrase.length(); i++){
if(currentPhrase.charAt(i)==str.charAt(0)){
if(currentPhrase.substring(i,str.length()+i).equals(str))
a++;
if(a==n){
return i;
}
}
}

return -1;
}

public static void replaceNthOccurance (String str, int n, String repl){
int a=0;
String s="";

int loc= findNthOccurance(str,n);

if(loc!=-1)
currentPhrase =currentPhrase.substring(0, loc) + repl+ currentPhrase.substring(loc + str.length(), currentPhrase.length());
}

public static void main (String [] args){
replaceNthOccurance("at", 1, "rane");
System.out.println(currentPhrase);
}

}
``````