FRQ 2017
(a)
This frq is trying to go over how to use specific methods and alter them in order to change a substring
- the method replaceNthOccurrence is asked to be written to change the nth occurrence of a substring with a replacement string, str with repl
- Methods:
A method in Java is a block of code that, when called, performs specific actions mentioned in it. You can insert values or parameters into methods, and they will only be executed when called. A method is similar to a function.
- Control Structures:
Control Structures can be considered as the building blocks of computer programs. A program is usually not limited to a linear sequence of instructions since during its process it may bifurcate, repeat code or bypass sections.
public void replaceNthOccurrence(String str, int n, String repl){
int i = findNthOccurrence(str, n);
if(i != -1)
{
String a = currentPhrase.substring(0, i);
//find the string from first index up till i
String b = currentPhrase.substring(i+str.length());
//everything after the str
currentPhrase = a + repl + b;
}
}
Answer for (a)
//Part (a)
public void replaceNthOccurrence(String str, int n, String repl)
{
int loc = findNthOccurrence(str, n);
if (loc != -1)
{
currentPhrase = currentPhrase.substring(0, loc) + repl + currentPhrase.substring(loc + str.length());
}
}
//comments on things