Partial String Replacement in C
Replacing specific sections of a string is a common task in programming. This article explores how to perform such replacements using the standard C libraries.
Initially proposed using the Qt framework, which provides a specific replace method, we delve into the standard library approach.
Standard Library Solution
The standard library offers the find and replace functions separately. By combining these functions, we can implement a replacement mechanism:
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; } int main() { std::string string("hello $name"); replace(string, "$name", "Somename"); return 0; }
Replacing All Occurrences
To replace all occurrences of a substring, we can use a loop to iterate through the string and perform replacements accordingly:
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(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } }
The above is the detailed content of How to Perform Partial String Replacement in C ?. For more information, please follow other related articles on the PHP Chinese website!