Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose somePhrase is any String, and assume that it has already been created. A

ID: 3936415 • Letter: S

Question

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.

Explanation / Answer

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);
     }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote