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

时间:2023-03-08 22:21:06
c++ 字符串函数用法举例
  • 1. substr()
  • 2. replace()
  • 例子:split()

字符串切割: substr

函数原型:

string substr ( size_t pos = , 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() << endl;
cout << s.substr(, ) << 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(, , "mmmmm");
cout << m << endl;
}

结果:hmmmmmlo

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "hello";
char a[] = "";
string m = s.replace(, , a);
cout << m << endl;
}

结果:h12345lo

举例

split()函数

#include <iostream>
#include <vector>
using namespace std; vector<string> split(const string &s, const string &delim)
{
vector<string> elems;
size_t pos = ;
size_t len = s.length();
size_t delim_len = delim.length();
if (delim_len == )
{
elems.push_back(s.substr(, len));
return elems;
}
while (pos < len)
{
int find_pos = s.find(delim, pos);
if (find_pos < )
{
elems.push_back(s.substr(pos, len-pos));
break;
}
elems.push_back(s.substr(pos, find_pos-pos));
pos = find_pos + delim_len;
}
return elems;
} int main()
{
vector<string> vec = split("hello^nihao^ohyi", "^");
for (int i = ; i < vec.size(); ++i)
cout << vec[i] << endl;
}