Implement the following method: public static String replacement(String ori, Str
ID: 3909761 • Letter: I
Question
Implement the following method: public static String replacement(String ori, String r, String w) This method should replace all occurrences of the String r witlh String w if the total length of String r (number of occurrenceX r. length()) is less than 30% of thelength of ori String; otherwise, you are going to replace all occurrences of w with r. Then return a String after applying these rules. For example replacement( "Skiing is fun", "fun", "cool") should returrn Skiing is cool replacement( " AA ABB" , "A" , "C" ) should return "AAABB" replacement( "AAABB","A" , "B") should return "AAAAA"Explanation / Answer
Below is your code
public class Replacement {
public static void main(String[] args) {
System.out.println(replacement("skiing is fun", "fun", "cool"));
System.out.println(replacement("AAABB", "A", "C"));
System.out.println(replacement("AAABB", "A", "B"));
}
/*
* Replacement method to replace all all occurrence of the String r with
* String w if the total length of String r (number of occurrences X
* r.length())
*
* is less than 30% of the length of ori String; otherwise, you are going to
* replace all occurrences of w with r.
*/
public static String replacement(String ori, String r, String w) {
int oriLength = ori.length();// Getting length of the orginal string
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = ori.indexOf(r,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += r.length();
}
}
int rCount = count;
double percentage = (rCount * 100 / (double)oriLength);// Calculating
// Percentage
// Checking if percentage is under 30 but not less 0
if (percentage >= 0 && percentage < 30) {
return ori.replaceAll(r , w);// If percentage is less
// than 30 then replace
// string r with w ""
// is used for Matching
// the word boundaries
// when outside the
// brackets.
} else {
return ori.replaceAll( w , r);// Replacing w with r
// when percentage is
// equal or greater than
// 30.
}
}
}
Output
skiing is cool
AAABB
AAAAA