Replace character in string at a particular index in C++

In this article, we will discuss different ways to replace a character in string at a particular index in C++.

Table Of Contents

Introduction

There can be two situations while replacing any character in a given string:

  1. The index of the character to be replaced and the new character are given as input.
  2. The character to be replaced and the new character are given as input.

Case 1: The index of the character to be replaced and the new character are given as input.

Using std::string::replace()

std::string::replace is a function in the C++ standard library that allows you to replace a portion of a string with a new string. It is a member function of the std::string class, so you can call it on any std::string object.

The replace function takes four arguments: the starting index, the number of characters to replace, the number of characters to insert, and the character to insert. In this case, we are replacing a single character (1) with a single character (new_char), so we pass 1 as the second and third arguments.

Advertisements

Algorithm

  1. Include the necessary headers (e.g. and ).
  2. Prompt the user to input a desired string.
  3. Take the input for the index of the character that has to be replaced and the new character to be replaced with.
  4. Use the std::string::replace function to replace the character at the desired index with the new character.
  5. Output the modified string using std::cout.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
  // Get input string
  string str;
  cout << "Enter a string: ";
  getline(cin, str);

  // Get index and new character
  size_t index;
  char new_char;
  cout << "Enter an index: ";
  cin >> index;
  cout << "Enter a new character: ";
  cin >> new_char;

  // Replace the character at the specified index
  str.replace(index, 1, 1, new_char);

  // Print the modified string
  cout << "Modified string: " << str << endl;

  return 0;
}

Output

Enter a string: abcdef 
Enter an index: 3
Enter a new character: z
Modified string: abczef

Time Complexity – O(N)

N is the length of the input string.
In the standard implementation of std::string::replace, the time complexity is linear in the length of the string. This means that the time taken to execute the function increases proportionally with the length of the string. Although for single characters it will tend to O(1) we are considering the worst-case time complexity.

Note
1. replace does not modify the original string in place; it returns a new string with the desired changes.
2. If we provide an index greater than the length of the string replace function gives out of range error.

Using the [] operator

In C++, strings are generally considered mutable, which means that they can be modified after they are created.

Thus an easier way to modify a string in C++ is to use the [] operator, which allows you to access and modify individual characters in the string.

Algorithm

  1. Read a string from the user and store it in a variable.
  2. Read the index of the character to be replaced and the new character from the user.
  3. Replace the character at the given index in the string with the new character.
  4. Display the modified string to the user.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
  string str;
  cout << "Enter a string: ";
  getline(cin, str);

  int index;
  cout << "Enter the index of the character to be replaced: ";
  cin >> index;

  char ch;
  cout << "Enter the new character: ";
  cin >> ch;

  str[index] = ch;
  cout << "Modified string: " << str << endl;

  return 0;
}

Output

Enter a string: abcdef
Enter the index of the character to be replaced: 3
Enter the new character: z
Modified string: abczef

Time Complexity – O(1)

This is because the program only performs a single operation: replacing a character at a given index in a string.

Case 2: The character to be replaced and the new character are given as input.

Using the [] operator

The following replaces all occurrences of the character in the string with the new character:

Algorithm

  1. Prompt the user to enter a string, the character to be replaced, and the new character.
  2. Store the string, old character, and new character in variables.
  3. Iterate through the string, character by character.
  4. For each character in the string:
    If the character is the old character, replace it with the new character.
  5. Print the modified string to the console.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
  string s;
  char oldChar, newChar;

  cout << "Enter a string: ";
  getline(cin, s);

  cout << "Enter the character to be replaced: ";
  cin >> oldChar;

  cout << "Enter the new character: ";
  cin >> newChar;

  // Replace all occurrences of the old character with the new character
  for (int i = 0; i < s.length(); i++) {
    if (s[i] == oldChar) {
      s[i] = newChar;
    }
  }

  cout << "Modified string: " << s << endl;

  return 0;
}

Output

Enter a string: abcabc
Enter the character to be replaced: b
Enter the new character: z
Modified string: azcazc

Time Complexity – O(N)

N is the length of the input string.
This is because the program performs a constant amount of work for each character in the string, and the number of characters in the string determines the total amount of work.

Note
To replace only the first occurrence break the loop after the first replacement is done using a boolean variable which is false initially and changes to true when the first replacement happens.

Using find()

The find() function is a member function of the std::string class in C++ that searches a string for a specified character or substring.
It takes two arguments:
1. The character or substring to search for, and
2. An optional starting position for the search.

If the character or substring is found, the find() function returns the position of the first occurrence in the string. If the character or substring is not found, the find() function returns the special value std::string::npos, which is a constant defined by the string class.

Algorithm

  1. Prompt the user to enter a string, the character to be replaced, and the new character.
  2. Store the string, old character, and new character in variables.
  3. Find the position of the first occurrence of the old character in the string using the find() function.
  4. While the old character is found in the string:
    Replace the character at the current position with the new character.
  5. Find the position of the next occurrence of the old character in the string using the find() function, starting from the character immediately after the current position.
  6. Print the modified string to the console.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
  string s;
  char oldChar, newChar;

  cout << "Enter a string: ";
  getline(cin, s);

  cout << "Enter the character to be replaced: ";
  cin >> oldChar;

  cout << "Enter the new character: ";
  cin >> newChar;

  // Find the first occurrence of the old character
  size_t pos = s.find(oldChar);

  // Replace all occurrences of the old character with the new character
  while (pos != string::npos) {
    s[pos] = newChar;
    pos = s.find(oldChar, pos + 1);
  }

  cout << "Modified string: " << s << endl;

  return 0;
}

Output

Enter a string: abcabc
Enter the character to be replaced: b
Enter the new character: z
Modified string: azcazc

Time Complexity – O(N)

  • N is the length of the input string.
    This is because the program performs a constant amount of work for each character in the string, and the number of characters in the string determines the total amount of work.

Note

To replace only the first occurrence replace the while loop with,

if(pos != string::npos)
{
  s[pos] = newChar;
}

Summary

In this article, we learned how to replace a single character of a string in various cases of inputs given. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top