About implementing rny_string (with.Java)
In this article, we learned about implementing rny_string.
We’ll do this by solving coding test problems, reflecting on the problems we solved, and learning about other ways to solve them.
Let’s start with the problem
Problem
We want to play a trick on a string by taking advantage of the fact that “m” and “rn” look similar.
Given a string rny_string, write a solution function that returns a string with all the “m”s in rny_string replaced with “rn”.
Example input and output
rny_string | result |
---|---|
“masterpiece” | “rnasterpiece” |
“programmers” | “programmers” |
“jerry” | “jerry” |
“burn” | “burn” |
My solution to the problem
class Solution {
public String solution(String rny_string) {
StringBuilder answer = new StringBuilder(rny_string);
for(int i = 0; i < answer.length(); i++){
if(answer.charAt(i) == 'm'){
answer.replace(i,i,"rn");
}
}
} return answer.toString();
}
}
Solution
StringBuilder answer = new StringBuilder(rny_string);: Converts the given string rny_string into a StringBuilder object that can be modified. StringBuilder is a class for efficiently modifying strings.
for(int i = 0; i < answer.length(); i++): Starts a loop that traverses the string character by character. The loop is repeated for the length of the string.
if(answer.charAt(i) == ‘m’): Checks if the character at the current index i is ‘m’.
answer.replace(i, i + 1, “rn”);: Replace ‘m’ with “rn” The replace method replaces the string between starting index i and ending index i + 1 with “rn”.
return answer.toString();: Converts the StringBuilder object back to a string and returns the result.
The code implemented in this way generates and returns a new string by replacing all the “m” characters in the input string with “rn”. We are working efficiently by using StringBuilder for string modification.