C++ Program to Replace a Character at a Specific Index

Strings are a collection of characters. We can also say them as character arrays. Considering an array of characters as strings, the strings have specified indices and values. Sometimes we can perform some modification on strings, one such modification is replacing characters by providing a specific index. In this article, we will see how to replace a character from a specific index inside a string using C++.


String_variable[ <given index> ] = <new character>

In C++ we can access the string characters using indices. Here to replace a character with some other character at a specified index, we simply assign that position with the new character as shown in the syntax. Let us see the algorithm for a better understanding.


  • Take the string s, specified index i, and a new character c
  • if the index i is positive and its value is not exceeding the string size, then
    • s[ i ] = c
    • return s
  • otherwise
    • return s without changing anything
  • end if


#include <iostream>
using namespace std;
string solve( string s, int index, char new_char){
   // replace new_char with the existing character at s[index]
   if( index >= 0 && index < s.length() ) {
      s[ index ] = new_char;
      return s;
   } else {
      return s;
int main(){
   string s = "This is a sample string.";
   cout << "Given String: " << s << endl;
   cout << "Replace 8th character with X." << endl;
   s = solve( s, 8, 'X' );
   cout << "Updated String: " << s << endl;
   cout << "Replace 12th character with ?." << endl;
   s = solve( s, 12, '?' );
   cout << "Updated String: " << s << endl;


Given String: This is a sample string.
Replace 8th character with X.
Updated String: This is X sample string.
Replace 12th character with ?.
Updated String: This is X sa?ple string.


Replacing characters at a specified index is simple enough in C++. C++ strings are mutable, so we can change them directly. In some other languages like java, the strings are not mutable. There is no scope to replace a character inside it by assigning a new character to it. In such cases, a new string needs to be created. A similar will happen if we define strings as character pointers like in C. Here in our example, we have defined a function to replace a character at the given index position. If the given index is out of scope, it will return the string and it will remain unchanged.

Updated on: 14-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started