This post will discuss how to replace a character at a particular index in a string in C++.

1. Using [] operator

The simplest and most intuitive way to replace a character in a string at a given index is to use the indexing operator []. This operator allows us to access and modify any character in a string by its position, starting from zero. For example, the following code replaces the character at index 5 in the given string with a space:

Download  Run Code

 
The indexing operator is very easy to use and understand. However, it does not check if the index is valid or within the bounds of the string. If we try to access or modify an invalid index, such as a negative number or a number greater than or equal to the length of the string, we will get undefined behavior, which may result in a runtime error, a wrong output, or even a security vulnerability. Therefore, we should only use the indexing operator when we are sure that the index is valid and within the bounds of the string.

2. Using string::at function

Another option to replace a character at a particular index in a string is to use the string::at function. This function is similar to the indexing operator, but with one important difference: it checks if the index is valid and within the bounds of the string. If it is not, it throws an out_of_range exception, which we can catch and handle accordingly. This makes our code more robust and secure, as we can avoid undefined behavior and handle errors gracefully. For example:

Download  Run Code

3. Using string::replace function

The third option to replace a character at a particular index in a string is using the string::replace function. This function allows us to replace a part of a string with another string, starting from a given position and for a given length. For example, the following code replaces the character at index 5 in the string with a space:

Download  Run Code

 
Unlike the indexing operator, the string::replace function throws an exception if the index is out of bounds, the resulting string would exceed the maximum permissible size, memory allocation fails, etc. However, it is more verbose and less intuitive than the indexing operator.

That’s all about replacing a character at a particular index in a string in C++.