Home >Backend Development >C++ >How Can I Replace Parts of a String in C ?
Replacing a String Segment with a New String
In C , replacing a part of a string with another string requires a combination of operations. While some libraries offer a dedicated replace() function for direct replacements, here's how you can approach it using standard C functions:
Using find() and replace() Functions
The find() function locates the position of a substring within a string. By combining this with the replace() function, which replaces a specified range with another string, you can effectively replace a part of the string:
bool replace(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } std::string string("hello $name"); replace(string, "$name", "Somename");
This approach replaces the first occurrence of the substring "$name" with "Somename."
Replacing All Occurrences with replaceAll
To replace all occurrences of a substring, you can extend the replace() method to search for and replace multiple instances within the string:
void replaceAll(std::string& str, const std::string& from, const std::string& to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Adjust start position if 'to' contains 'from' } }
This function performs a successive replacement of all occurrences of the substring "from" with the string "to" within the given string.
The above is the detailed content of How Can I Replace Parts of a String in C ?. For more information, please follow other related articles on the PHP Chinese website!