How can I remove a character at a specified position in Apex in String?
4 Answers
As a generic function, you can write this:
static string removeChar(String source, Integer index) {
return source.left(index)+source.right(source.length()-index-1);
}
This just removes the one character specified by index.
Another way would be to convert it into char array, remove the character and convert back into a string.
String oldName ='Pranay';
Integer [] nameArray =oldName.getChars();
nameArray.remove(3);
String newName = String.fromCharArray(nameArray);
System.debug(oldName); //prints Pranay
System.debug(newName); //prints Praay
You can use mid for that.
String s1 = 'abcde';
system.debug(s1.mid(0,3) + s1.mid(4,100));
You will remove the char in the position 4 in this case.
Just for fun, another approach can be using substring.
static string removeChar(String source, Integer index) {
return source.substring(0,index)+source.substring(index+1);
}