标签:style blog color os io strong ar div
字符串切割: substr
函数原型:
string substr ( size_t pos = 0, size_t n = npos ) const;
解释:抽取字符串中从pos(默认为0)开始,长度为npos的子字串
#include <iostream> #include <string> using namespace std; int main() { string s = "hello";
cout << s.substr() << endl; cout << s.substr(2) << endl; cout << s.substr(2, 2) << endl;
cout << s.substr(2, string::npos) << endl; }
结果
hello
llo
ll
llo
注意:string 类将 npos 定义为保证大于任何有效下标的值
字符串替换:replace
函数原型:
basic string& replace(size_ type Pos1, size_type Num1, const type* Ptr ); basic string& replace(size_ type Pos1, size_type Num1,const string Str );
替换用Ptr(或str)替换字符串从Pos1开始的Num1个位置
#include <iostream> #include <string> using namespace std; int main() { string s = "hello"; string m = s.replace(1, 2, "mmmmm"); cout << m << endl; }
结果:hmmmmmlo
另
#include <iostream> #include <string> using namespace std; int main() { string s = "hello"; char a[] = "12345"; string m = s.replace(1, 2, a); cout << m << endl; }
结果:h12345lo
标签:style blog color os io strong ar div
原文地址:http://www.cnblogs.com/kaituorensheng/p/3891621.html