Table of Contents
Example Example
illustrate
method one
algorithm
Example
Output
Method Two
Home Backend Development C++ Modifies a string by replacing all occurrences of a given character with a specified replacement character

Modifies a string by replacing all occurrences of a given character with a specified replacement character

Sep 08, 2023 am 10:17 AM
Character replacement Replace character String modification

Modifies a string by replacing all occurrences of a given character with a specified replacement character

In this question we need to replace the characters of a given string based on the given characters in the character pair array. We will discuss two different solutions. In the first method, we replace each character by iterating over the characters and character pairs of the given string.

In the second method, we will use an array of length 26 to store the replacement characters associated with each character and change the characters of the given string.

Problem Statement − We are given a string str containing N lowercase alphabetic characters. Also, we are given an array containing pairs of characters. We need to replace pairs[i][0] characters in the given string with pairs[i][1].

Example Example

Input –  str = "xyz", pairs = {{'x', 'a'}, {'y', 'b'},, {'z', 'c'}}
Copy after login
Output – ‘abc’
Copy after login

illustrate

Here, 'x' is replaced with 'a', 'y' is replaced with 'b', and 'z' is replaced with 'c'.

Input – str = "abderb", pairs = {{'a', 'e'}, {'b', 't'}, {'e', 'f'}, {'r', 's'}}
Copy after login
Output – ‘etdfst’
Copy after login

illustrate

In the string, 'a' is replaced with 'e', ​​'b' is replaced with 't', 'e' is replaced with 'f', and 'r' is replaced with 's'.

method one

In this method, we will iterate over each pair of characters and replace the matching characters in the given string. We need two nested loops to iterate over the string for each loop.

algorithm

  • Step 1 - Store the size of the string in variable 'N' and the array in variable 'M'.

  • Step 2 - Store a copy of the string in the 'temp' variable.

  • Step 3 - Use a for loop to iterate through the list of pairs.

  • Step 4 − In the loop, store the first character in variable ‘a’ and the second character in variable ‘b’.

  • Step 5 - Iterate over the string using nested loops.

  • Step 6 − In the nested loop, if the current character of the given string is equal to 'a', replace the current character with 'b' in the temporary string.

  • Step 7 - Return the value of temp.

Example

#include <bits/stdc++.h>
using namespace std;
string replaceChars(string str, vector<vector<char>> pairs){
   // stror the size of the string and the array
   int N = str.size(), M = pairs.size();
   
   // Create a copy of the string str
   string temp = str;
   
   // Iterate over the array
   for (int x = 0; x < M; x++){
   
      // store the characters from the pair
      char a = pairs[x][0], b = pairs[x][1];
      
      // iterate over the string
      for (int y = 0; y < N; y++){
      
         // If the character is equal to a, then replace it with b
         if (str[y] == a){
            temp[y] = b;
         }
      }
   }
   return temp;
}
int main(){
   string str = "abderb";
   vector<vector<char>> pairs{{'a', 'e'},
      {'b', 't'},
      {'e', 'f'},
      {'r', 's'}};
   cout << "The string after replacing with the given characters is - " << replaceChars(str, pairs);
   return 0;
}
Copy after login

Output

The string after replacing with the given characters is - etdfst	
Copy after login

Time complexity - O(N*M), where N is the length of the string and M is the length of the character pair array.

Space complexity - O(N), since we store the new string in the temp variable.

Method Two

In this method, we can create an array of size 26. We can then store the replaceable character at the current character's position. Finally, we can take the replaceable elements from the array and update each character of the string.

algorithm

  • Step 1 - Get string size as 'N' and array size as 'M'.

  • Step 2 - Define "initial" and "final" arrays of length 26.

  • Step 3 - Loop through the string and store str[Y] in the initial and final array index of "str[Y] - a". Here, str[Y] - 'a' gives an index between 0 and 25 based on the ASCII value of the character.

  • The reason for storing str[Y] at 'str[Y] - a' position in initial and final array is that if any character is present in the string but not in the character pair, we can Leave it unchanged.

  • Step 4 - Iterate over the given array of character pairs. Within the loop, use nested loops to iterate over the initial array. If the first character of the current pair is equal to the character of the "initial" array, the characters of the "final" array are updated with the second character of the current pair.

  • Step 5 − Define the ‘result’ variable and initialize it to an empty string.

  • Step 6 - Iterate through the input string, get the corresponding character of the current character from the "final" array, and append it to the "result" string.

  • Step 7 - Return the 'result' string.

Example

#include <bits/stdc++.h>
using namespace std;
//  Function to replace the characters in the string
string replaceChars(string str, vector<vector<char>> pairs){

   // getting the size of the string and the vector
   int N = str.size(), M = pairs.size();
   
   // Declare two arrays of size 26
   char initial[26];
   char final[26];
   
   // Check all existing characters in the string
   for (int Y = 0; Y < N; Y++){
      initial[str[Y] - 'a'] = str[Y]; final[str[Y] - 'a'] = str[Y];
   }
   
   // Iterate over the range [0, M]
   for (int X = 0; X < M; X++){
   
      // get characters from the vector
      char a = pairs[X][0], b = pairs[X][1];
      
      // Iterate over the range [0, 26]
      for (int Y = 0; Y < 26; Y++){
      
         // If the character is the same as a, then replace it with b in the final array
         if (initial[Y] == a){
            final[Y] = b;
         }
      }
   }
   string result = "";
   
   // get the final string using the final array
   for (int Y = 0; Y < N; Y++){
      result += final[str[Y] - 'a'];
   }
   return result;
}
int main(){
   string str = "aberb";
   vector<vector<char>> pairs{{'a', 'e'},
      {'b', 't'},
      {'e', 'f'},
      {'r', 's'}};
   cout << "The string after replacing with the given characters is - " << replaceChars(str, pairs);
   return 0;
}
Copy after login

Output

The string after replacing with the given characters is - etfst
Copy after login

Time complexity - O(N), as nested loop, constant iteration only.

Space complexity - O(1), since it uses an array of length 26, which is constant.

The above is the detailed content of Modifies a string by replacing all occurrences of a given character with a specified replacement character. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to replace specific characters in a string with other characters in PHP using regular expressions How to replace specific characters in a string with other characters in PHP using regular expressions Jun 23, 2023 am 09:46 AM

In PHP, regular expressions are a very powerful tool that can help us process and convert strings easily. Using regular expressions, you can achieve efficient and flexible operations on strings, such as finding strings with specific patterns, replacing matching strings, etc. In this article, we will discuss how to use regular expressions to replace specific characters in a string with other characters. This is a common need, such as replacing HTML tags in a piece of text with plain text, or replacing Emoji tables in a piece of text.

Python program: Trim string from right side of string Python program: Trim string from right side of string Sep 08, 2023 pm 06:21 PM

In Python, we have a predefined function rstrip() to remove the characters on the right side. This means it will remove spaces on the right side of the string. Let us take an example to understand how to trim from the left side of a string. Removes the right string LESS from the given string "WIRELESS" and gets the resulting value as "WIRE". In the given string "kingdom", delete the string dom on the right side and get the result value as "king". Syntax The syntax used in the following examples is −isspace() which is a predefined method in Python to allow whitespace, newlines, or spaces in characters. rstrip("parameterasastri

C++ program: replace character at specific index C++ program: replace character at specific index Aug 25, 2023 pm 10:53 PM

A string is a set of characters. We can also call them character arrays. Consider a character array consisting of strings with specified indices and values. Sometimes we can make some modifications to the string, one of the modifications is to replace 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++. Syntax String_variable[&lt;givenindex&gt;]=&lt;newcharacter&gt; In C++, we can access string characters using index. exist

Write a program in Java to replace all characters in a file with '#' except specific words Write a program in Java to replace all characters in a file with '#' except specific words Sep 13, 2023 am 08:57 AM

The split() method of String class. Split the current string into matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or terminates at the end of the string. The replaceAll() method of String class accepts two strings representing regular expressions and a replacement string and replaces the matching value with the given string. Replace all characters in the file except specific words with "#" (one way) - read the contents of the file into a string. Create an empty StringBuffer object. Use the split() method to split the obtained string into a String array. all over

Python program to replace characters at specific index Python program to replace characters at specific index Aug 19, 2023 am 09:41 AM

In Python, we can easily replace a character at a specific index by converting the string into a list of characters, using the list() method. We then modify the character at the desired index and use the join() method to convert the list back to a string. We can also replace characters at specific indexes using slice and replace methods. In this article, we will see an example of replacing a character at a specific index in Python using list and join method, slicing method and replace method. Method 1: Use the list() and join() method syntax list() method list(sequence) The list() method accepts a sequence (such as a string, tuple, or set) as a parameter and returns a specific

Modifies a string by replacing all occurrences of a given character with a specified replacement character Modifies a string by replacing all occurrences of a given character with a specified replacement character Sep 08, 2023 am 10:17 AM

In this problem, we need to replace the characters of a given string based on the given characters in the array of character pairs. We will discuss two different solutions. In the first method, we replace each character by iterating over the characters and character pairs of the given string. In the second method, we will use an array of length 26 to store the replacement characters associated with each character and change the characters of the given string. Problem Statement − We are given a string str containing N lowercase alphabetic characters. Also, we are given an array containing pairs of characters. We need to replace pairs[i][0] characters in the given string with pairs[i][1]. ExampleInput–str="xyz"

Minimize replacement of a character to its nearest letter, making the string a palindrome Minimize replacement of a character to its nearest letter, making the string a palindrome Sep 15, 2023 pm 12:25 PM

In this article, we will discuss an interesting algorithmic problem: "Minimize the replacement of a character with its nearest alphabet to make a string palindrome." This problem is interesting because it involves string manipulation, palindrome checking, and The concept of character ASCII values. Let’s delve deeper into this issue. Problem Statement Given a string, the task is to convert it into a palindrome with minimum number of substitutions. These substitutions are accomplished by changing characters to their closest alphabet. Comprehension Questions A palindrome is a sequence of words, phrases, numbers, or other characters that is read backwards the same as forwards. Our goal is to minimize the total number of substitutions required to convert a given string into a palindrome. For example, consider the string "abc". To convert it to a palindrome we can convert "

How to use Vue form processing to implement character replacement in form fields How to use Vue form processing to implement character replacement in form fields Aug 10, 2023 pm 05:37 PM

How to use Vue form processing to implement character replacement in form fields When developing web applications, forms are an essential part. In some scenarios, we may need to replace characters entered by the user to meet data format requirements or implement certain functions. As a popular front-end framework, Vue.js provides powerful data binding and processing capabilities, making form processing more convenient. This article will introduce how to use Vue.js to implement the character replacement function of form fields and provide code examples. first,

See all articles