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;
}
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 withcharAt(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: