How to replace all occurrences of a character in string?
How to Replace All Occurrences of a Character in a String
Replacing all occurrences of a character in a string is a common operation in many programming languages. Here’s how you can achieve this in a variety of languages, including Python, Java, JavaScript, and C++.
Python
In Python, you can use the built-in str.replace()
method to replace all occurrences of a character in a string.
# Using str.replace() method original_string = "hello world" modified_string = original_string.replace('l', 'x') print(modified_string) # Output: hexxo worxd
Java
In Java, you can use the String.replace()
method, which replaces all occurrences of a specified character with another character.
public class Main { public static void main(String[] args) { String originalString = "hello world"; String modifiedString = originalString.replace('l', 'x'); System.out.println(modifiedString); // Output: hexxo worxd } }
JavaScript
In JavaScript, you can use the String.prototype.replace()
method along with a global regular expression to replace all occurrences of a character.
// Using String.prototype.replace() with a global regular expression let originalString = "hello world"; let modifiedString = originalString.replace(/l/g, 'x'); console.log(modifiedString); // Output: hexxo worxd
C++
In C++, you can replace characters in a string using the std::replace
algorithm from the <algorithm>
library.
#include <iostream> #include <string> #include <algorithm> int main() { std::string originalString = "hello world"; std::replace(originalString.begin(), originalString.end(), 'l', 'x'); std::cout << originalString << std::endl; // Output: hexxo worxd return 0; }
Summary
- Python: Use
str.replace('old_char', 'new_char')
. - Java: Use
String.replace('old_char', 'new_char')
. - JavaScript: Use
String.prototype.replace(/old_char/g, 'new_char')
. - C++: Use
std::replace
from the<algorithm>
library.
Each method is idiomatic to the language it is used in and provides an efficient way to replace characters in a string. For more in-depth knowledge and practical examples on programming concepts, consider exploring Grokking the Coding Interview on DesignGurus.io, which provides comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog