C++字串查詢和替換
//This is ...
#include<bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
using namespace std;
void string_replace(string &str, const string old0, const string new0);
int main(int argc, char* argv[])
{
string str = "--++---Hello World---++--";
string strKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghikjlmnopqrstuvwxyz";
string::size_type nPos0 = str.find_first_of(strKey);
if(nPos0 == string::npos) return -1;
string::size_type nPos1 = str.find_last_of(strKey);
if(nPos1 == string::npos) return -1;
string newstr = str.substr(nPos0, nPos1 - nPos0 + 1);
cout <<"ner string: " <<newstr << endl;
string str2 = "abc12123xyz-abc12123xyz";
string_replace(str2, "12", "98");
cout << str2 << endl;
return 0;
}
void string_replace(string &str, const string old0, const string new0)
{
string::size_type nPos = 0;
string::size_type nsrclen = old0.size();
string::size_type ndstlen = new0.size();
while(nPos = str.find(old0, nPos))
{
if(nPos == string::npos) break;
str.replace(nPos, nsrclen, new0);
nPos += ndstlen;
}
}