c++ replace character in string
C++ Replace Character in String:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char oldChar = 'o';
char newChar = '0';
for (char& c : str) {
if (c == oldChar) {
c = newChar;
}
}
std::cout << str << std::endl;
return 0;
}
- Include Necessary Libraries: Include the necessary header files for input/output and string manipulation.
- Define Main Function: Define the main function as the entry point of the program.
- Initialize String: Initialize a string variable with the value "Hello, world!".
- Define Old and New Characters: Define the old character to be replaced and the new character to replace it with.
- Iterate Through String: Use a for loop to iterate through each character in the string.
- Check for Old Character: Check if the current character is equal to the old character.
- Replace Character: If the old character is found, replace it with the new character.
- Print Modified String: Print the modified string after the character replacement.
- Return 0: Return 0 to indicate successful program execution.