Set characters at a specific position within the string in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

In case you don’t want to overwrite a string, but just change a character at a specific position, Arduino provides the setCharAt() function exactly for that.


String1.setCharAt(ind, new_char);

String 1 is the string to modify. ind is the index where the character needs to be set. new_char is the value of the new character that needs to be set.

This function returns nothing, and modifies the string in place.


The following example illustrates the use of this function.

void setup() {
   // put your setup code here, to run once:

   String string1 = "Hello World!";

void loop() {
   // put your main code here, to run repeatedly:


The Serial Monitor output is shown below −

As you can see, in the first two cases, we set characters within the length of the string, and they got set at the correct indices (string index starts at 0). When we tried to set a character outside the length of the string, it had no effect on the string. Thus, this experiment also shows that this function cannot be used to extend the length of a string. You should only set characters within the existing length of a string.

Updated on 29-May-2021 13:30:39