首页 > 代码库 > c++ 字符串函数用法举例

c++ 字符串函数用法举例

字符串切割: 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
lloll
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