CodeLab Solution 20859




CS125 CodeLab Solutions

CodeLab Solution 20859

Write a recursive, string -valued method , replace, that accepts a string and returns a new string consisting of the original string with each blank replaced with an asterisk (*)

Replacing the blanks in a string involves:

Nothing if the string is empty
Otherwise:
If the first character is not a blank, simply concatenate it with the result of replacing the rest of the string
If the first character IS a blank, concatenate an * with the result of replacing the rest of the string

[cc lang=”JAVA”] public String replace(String sentence)
{
if(sentence.isEmpty())
return sentence;
if(sentence.charAt(0) == ‘ ‘)
return ‘*’ + replace(sentence.substring(1,sentence.length()));
else
return sentence.charAt(0) + replace(sentence.substring(1,sentence.length()));
}
[/cc]


No Comments Yet.

Leave a comment

You must be Logged in to post a comment.