Set characters at a specific position within the string in Arduino


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.

Syntax

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.

Example

The following example illustrates the use of this function.

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   String string1 = "Hello World!";
   Serial.println(string1);
   string1.setCharAt(4,'p');
   Serial.println(string1);
   string1.setCharAt(11,'y');
   Serial.println(string1);
   string1.setCharAt(12,'i');
   Serial.println(string1);
}

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

Output

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

567 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements