Created
February 26, 2022 10:21
-
-
Save JaHIY/d2995eef1f78633b5135cf0c5c15f539 to your computer and use it in GitHub Desktop.
replaceAll function in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using std::cout; | |
using std::endl; | |
#include <string> | |
using std::string; | |
using std::basic_string; | |
#include <string_view> | |
using std::basic_string_view; | |
template <typename CharT> | |
basic_string<CharT>& replaceAll(basic_string<CharT>& str, basic_string_view<CharT> old_str, basic_string_view<CharT> new_str) { | |
typename basic_string_view<CharT>::size_type old_len(old_str.size()); | |
typename basic_string_view<CharT>::size_type new_len(new_str.size()); | |
typename basic_string<CharT>::size_type pos(0); | |
while ((pos = str.find(old_str, pos)) != basic_string<CharT>::npos) { | |
str.replace(pos, old_len, new_str); | |
pos += new_len; | |
} | |
return str; | |
} | |
int main(void) { | |
string a{"你好,世界!世界!!"}; | |
cout << replaceAll<char>(a, "世界", "地球人") << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment