105k views
2 votes
In a class named MidtermProblems, write a public static method named replaceFirst that takes in a String s and a char c as arguments. The method will return a modified String replacing the first character with the one that was passed in. (Do not print out the String)

Special cases:
If s is null, the method should return null.
If s is the blank string, "", the method should return the blank string.

Example:
Replace.replaceFirst("make", ‘t’);
Returns: "take"

Replace.replaceFirst("a", ‘x’);
Returns: "x"

User Matthieus
by
6.5k points

1 Answer

2 votes

Final answer:

In the MidtermProblems class, you should write a public static method called replaceFirst that takes in a String s and a char c as arguments. The method should return a modified String by replacing the first character with the one that was passed in.

Step-by-step explanation:

In the class named MidtermProblems, you should write a public static method called replaceFirst that takes in a String s and a char c as arguments. The method should return a modified String by replacing the first character with the one that was passed in. Here's an example:

public class MidtermProblems {
public static String replaceFirst(String s, char c) {
if (s == null) {
return null;
}
if (s.equals("")) {
return "";
}
// Convert String to char array
char[] chars = s.toCharArray();
// Replace the first character
chars[0] = c;
// Convert char array back to String
String result = new String(chars);
return result;
}
}

User Andy Macleod
by
6.6k points