0

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

1
  • Build a new string with everything before and everything after the character you don't want. Commented Nov 28, 2018 at 14:31

4 Answers 4

8

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.

4

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

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

2

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.

2

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .