public class
Phrase
{
private
String currentPhrase;
/** Constructs a new Phrase
object. */
public Phrase(String p)
{
currentPhrase = p;
}
/** Returns the index of the
nth occurrence of str in the current phrase;
* returns -1
if the nth occurrence does not exist.
* Precondition: str.length() > 0 and n > 0
* Postcondition: the current phrase is not
modified.
*/
public int findNthOccurrence(String str, int n)
{
int index = currentPhrase.indexOf(str);
int occ =
1;
while (index != -1 && occ
< n)
{
index = currentPhrase.indexOf(str, index+1);
occ++;
}
return index;
}
/** Modifies the current
phrase by replacing the nth occurrence of str with repl.
* If the nth occurrence does not exist,
the current phrase is unchanged.
* Precondition: str.length() > 0 and n > 0
*/
public void replaceNthOccurrence(String str, int n,
String repl)
{
int index = findNthOccurrence(str, n);
if (index != -1)
{
String before = currentPhrase.substring(0, index);
String after = currentPhrase.substring(index+str.length());
currentPhrase = before + repl + after;
}
}
/** Returns the index of the
last occurrence of str in the current phrase;
* returns -1
if str is not found.
* Precondition: str.length() > 0
* Postcondition: the current phrase is not
modified.
*/
public int findLastOccurrence(String str)
{
return currentPhrase.lastIndexOf(str);
}
/** Alternate solution in case
you were not aware of the lastIndexOf() method.
*/
public int findLastOccurrenceB(String str)
{
int i = currentPhrase.length() -
1;
int index = currentPhrase.indexOf(str, i);
while (index ==
-1 && i
>= 0)
{
index = currentPhrase.indexOf(str, i);
i--;
}
return index;
}
/** Returns a string
containing the current phrase. */
public
String toString()
{
return currentPhrase;
}
}
|