Write a Java program with a method public String replaceChar(String p, int k, char c) { } that given a String p, an int k, and a char c, returns a String with the kth character replaced by c. Of course, 0<=k<=p.length()-1, otherwise raise an exception or error.
//TestCode.java public class TestCode { public String replaceChar(String p, int k, char c) { String result = ""; for (int i = 0; i < p.length(); i++) { if (i == k) { result += c; } else { result += p.charAt(i); } } return result; } public static void main(String[] args) { TestCode t = new TestCode(); System.out.println(t.replaceChar("abcdefgh",2,'z')); } }
Get Answers For Free
Most questions answered within 1 hours.