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!\", newPhraseshould hold this:
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.
Solution
public class Driver{
public static void main(String []args){
//delcare somPhrase string
String somePhrase=\"How now - my good friend!\";
String newPhrase;
//create string builder object which holds somePhrase value
StringBuilder sb=new StringBuilder(somePhrase);
//loop through the object and replace \" \"occurances with $
for (int index = 0; index < sb.length(); index++) {
if (sb.charAt(index) == \' \') {
sb.setCharAt(index, \'$\');
}
}
//assign object value to newPhrase and display
newPhrase=sb.toString();
System.out.println(newPhrase);
}
}
