Suppose somePhrase is any String, and assume that it has already been created. A
ID: 3906589 • 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!", 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.
2. Suppose somePhrase is any String, and assume that it has already been created. Also, assume that a second String variable, anotherPhrase, has already been declared. Using the StringBuilder class, write code to place in anotherPhrase a palindrome version of somePhrase with a * character in the middle. For example, if somePhrase initially is "abcd", then anotherPhrase should ultimately hold "abcd*dcba"; and if somePhrase holds "Oh dear!", then ultimately anotherPhrase should hold "Oh dear!*!raed hO". When you've built the final version of anotherPhrase, then print it to the console. Hint: first make two distinct StringBuilder versions of somePhrase. Then reverse the second one and use the append method to assemble and then print your final answer. The reverse method is tricky. If s and t are StringBuilder variables, and if s references "xyz", then the statement t = s.reverse(); puts the reverse of "xyz", "yzx", in both s and t. Enter your sequence of commands, ending with a print statement, in the box below. help need in java
Explanation / Answer
As per the specifications, assuming that the String variables somePhrase, newPhrase and anotherPhrase are already declared somewhere in code.
Code for question 1:
=====
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(newPhrase);
==================
Code for question 2:
==============
StringBuilder s = new StringBuilder(somePhrase);
StringBuilder t = new StringBuilder(somePhrase);
t.reverse();
s.append("*");
s.append(t);
anotherPhrase = s.toString();
System.out.println(anotherPhrase);
=====================
Please do rate the answer if it helped. If any issues, let me know, I'll help.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.