Question:
Consider the following problem:
You are given a string, originalString, which contains a sequence of numbers and letters. Your task is to implement a function, manipulate_string(originalString), that performs the following operations:
targetLetter, with a given string, replacementString.Write the function manipulate_string(originalString) in Java, and provide a step-by-step explanation of how the function should be implemented.
Signature:
public static String manipulate_string(String originalString)
Input:
originalString (1 <= originalString.length <= 1000), which represents the original string containing numbers and letters.Output:
Example:
String originalString = "Hello World!";
String modifiedString = manipulate_string(originalString);
System.out.println(modifiedString);
Output:
!dlrow olleh
Explanation:
To implement the manipulate_string(originalString) function, follow these steps:
Step 1: Create a variable, modifiedString, and set it equal to an empty string. This variable will hold the modified string.
Step 2: Iterate over each character, ch, in the originalString.
Step 3: Inside the loop, perform the following checks and modifications:
Check if ch is an uppercase letter. Use the Character.isUpperCase(ch) method to determine this.
ch is uppercase, convert it to lowercase using the Character.toLowerCase(ch) method.ch, to the modifiedString.If ch is not an uppercase letter, append it to the modifiedString as it is.
Step 4: After the loop, reverse the modifiedString using the StringBuilder class. Convert modifiedString to a StringBuilder object using its constructor, then call the reverse() method on the StringBuilder object.
Step 5: Convert the reversed StringBuilder object back to a string using the toString() method and store the result in the modifiedString.
Step 6: Replace all occurrences of a specific letter, targetLetter, with a given string, replacementString. For example, if the targetLetter is 'o' and the replacementString is 'XYZ', replace all occurrences of 'o' in the modifiedString with 'XYZ'.
Step 7: Return the modified modifiedString.
Here is the Java implementation of the manipulate_string(originalString) function:
import java.util.*;
public class StringManipulation {
public static String manipulate_string(String originalString) {
String modifiedString = "";
for (char ch : originalString.toCharArray()) {
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
}
modifiedString += ch;
}
modifiedString = new StringBuilder(modifiedString).reverse().toString();
char targetLetter = 'o';
String replacementString = "XYZ";
modifiedString = modifiedString.replace(targetLetter, replacementString);
return modifiedString;
}
public static void main(String[] args) {
String originalString = "Hello World!";
String modifiedString = manipulate_string(originalString);
System.out.println(modifiedString);
}
}
Running the code will output the following:
!dlrow olleH