一段字符串给定2边特点的值,取出中间这段。比如:返回中间文本=str(前面文本,后面文本)我用string类没整明白。...
一段字符串 给定 2边特点的值,取出中间这段。
比如: 返回中间文本 = str(前面文本,后面文本) 我用string类 没整明白。
// C++ string 实现的取中间串函数
string get_mid_str(const string & _src, const string & _front, const string & _rear)
{
size_tpos_1, pos_2;
string mid_str;
pos_1 = _src.find_first_of(_front, 0); // 找到前面文本
pos_2 = _src.find_last_of(_rear, _src.length()); // 找到后面文本
if(pos_1 != string::npos && pos_2 != string::npos)
{ // 前后文本均找到
pos_1 += _front.length(); // 起始位置
if(pos_1 < _src.length() && pos_2 > pos_1)
{ // 位置有效
mid_str = _src.substr(pos_1, pos_2 - pos_1); // 取目标串
}
}
return mid_str;
}
方法一:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("abcdefg");
string::iterator it;
for (it =str.begin(); it != str.end(); ++it)
{
if ( *it == 'c')
{
str.erase(it);
}
}
cout << str << endl;
}
方法二:
#include <string> #include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str = "abcdefg";
string::iterator new_end = remove_if(str.begin(), str.end(), bind2nd(equal_to<char>(), 'c'));
str.erase(new_end, str.end());
cout << str << endl;
return 0;
}
PS.
string.erase()方法删除迭代器指向的某个字符
// C++ string 实现的取中间串函数
string get_mid_str(const string & _src, const string & _front, const string & _rear)
{
size_tpos_1, pos_2;
string mid_str;
pos_1 = _src.find_first_of(_front, 0); // 找到前面文本
pos_2 = _src.find_last_of(_rear, _src.length()); // 找到后面文本
if(pos_1 != string::npos && pos_2 != string::npos)
{ // 前后文本均找到
pos_1 += _front.length(); // 起始位置
if(pos_1 < _src.length() && pos_2 > pos_1)
{ // 位置有效
mid_str = _src.substr(pos_1, pos_2 - pos_1); // 取目标串
}
}
return mid_str;
}