How can I remove a character at a specified position in Apex in String?

  • Build a new string with everything before and everything after the character you don't want. – Florian Heer Nov 28 '18 at 14:31

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();
String newName = String.fromCharArray(nameArray);
System.debug(oldName); //prints Pranay
System.debug(newName); //prints Praay

Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm


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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.