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

  • 1. substr()
  • 2. replace()
  • 例子:split()

 

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

函数原型:

1
2
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

 

举例

split()函数

复制代码
#include <iostream>
#include <vector>
using namespace std;

vector<string> split(const string &s, const string &delim)
{
    vector<string> elems;
    size_t pos = 0;
    size_t len = s.length();
    size_t delim_len = delim.length();
    if (delim_len == 0)
    {
        elems.push_back(s.substr(0, len));
        return elems;
    }
    while (pos < len)
    {
        int find_pos = s.find(delim, pos);
        if (find_pos < 0)
        {
            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 = 0; i < vec.size(); ++i)
        cout << vec[i] << endl;
}
复制代码

 




本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3891621.html,如需转载请自行联系原作者


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值