Replacing all characters with a certain character by loops

285 views Asked by At

For this classwork(as you can see i didn't finish it cause i have no clue how to start this) I am suppose to make a program that when the user enters his/her string, plus the character that replaces all characters with, it changes the characters of original string to a new one. For example, I would enter laptop, and i want to replace it with the letter I, so the new string would become I.

tobereplaced, a character that you want your string to be replaced replacedwith, is when the character from tobereplaced replaces the orginal string the user input. If its empty,null return original string, If it has a string and a character to replace then replace it.

/**
 * Replaces all instances of the character toBeReplaced 
 * with replacedWith in the String str. Remember str.charAt(int i) 
 * gives you the character at a location.
 * @param str
 * @param tobeReplaced
 * @param replacedWith
 * @return
 */
public static String replaceChar(String str, char tobeReplaced, char replacedWith)
{
    return str;
}
3

There are 3 answers

1
Blub On BEST ANSWER

Ok I suppose you are not allowed to use replaceAll() as that would make this task trivial ;-)

Now what you want to do is take a look at the String javadoc and figure out how you could replace a character using the method substring(int beginIndex, int endIndex).

And then you think of a way how you can combine that in a for loop with charAt(int index) which gives you the character at the specified index.

Actually you could also take a look at split() as that could be also used to replace a character:

String s = "halalo";
String [] split = s.split("a");  
// split now contains: split[0] = "h", split[1] = "l", split[2] = "lo"
5
Siva Atta On

The arguments of the method are little confusing. What is the difference between 'tobeReplaced' and 'replacedWith'?

If i understand the problem correctly, the method should accept two arguments:

  1. String input by the user
  2. Character input by the user that replaces the String.

I did not see any conditions being mentioned (like to replace only if string is not empty or only if string contains some characters etc). When there are no conditions, the method can simply return the character input received.

correct me, if my understanding is not right. Thanks.

10
Ingo On

This is an easy task, because only 3 cases can occur:

replaceChars(s, toBeReplaced, replacement)
  1. s is the empty string. Result is the empty string.
  2. s starts with the character that is to be replaced. Result is replacement + replaceChars(rest, toBeReplaced, replacement) where rest is s without the first character.
  3. s does not start with the character that is to be replaced. Result is first + replaceChars(rest, toBeReplaced, replacement) where firstis the first character of s and rest the rest of s, as before.