Suppose somePhrase is any String and assume that it has alre
Suppose somePhrase is any String, and assume that it has already been created. Assume also that the String variable newPhrase has already been declared. Using the StringBuilder class, replace all space characters in somePhrase with the dollar sign symbol $, and place the result in newPhrase. Then print newPhrase to the console. For example if somePhrase is the String \"How now - my good friend!\", newPhrase should hold this: How$now$-$my$good$friend! and that\'s what should be printed. Hint: first turn somePhrase into a StringBuilder object, and then traverse the object, changing each space character into a \'$\' as you go. Next, use the toString method in the StringBuilder class to create newPhrase. Enter your code in the box below.
Solution
StringReplace.java
import java.util.Scanner;
public class StringReplace {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter Some Phrase String: \");
String somePhrase = scan.nextLine();
String newPhrase;
StringBuilder sb = new StringBuilder(somePhrase);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == \' \') {
sb.setCharAt(i, \'$\');
}
}
newPhrase = sb.toString();
System.out.println(\"New Pharse String is : \"+newPhrase);
}
}
Output:
Enter Some Phrase String:
How now - my good friend!
New Pharse String is : How$now$-$my$good$friend!
