Problem:
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).
missingChar("kitten", 1) → "ktten"
missingChar("kitten", 0) → "itten"
missingChar("kitten", 4) → "kittn"
Solution:
//Well, we can make do with just creating a method
//that will return us a modified string that will take
//in our String and index
public String missingChar(String str, int n) {
//We can't remove things from a String variable, just add
//to it so we have to make a new string by taking two
//'slices' or substrings of that String but without including
//a certain index.
//Note: str.substring(a,b) gives us a new String starting
//from index 0 to index b-1, which is why n isn't in the new
//string and why length() doesn't cause any problems
return str.substring(0,n) + str.substring(n+1,str.length());
}
function missingChar(str, n){
ReplyDeletereturn str.replace(str.charAt(n), '');
}