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

函数原型:

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;
}

 

posted @ 2014-08-07 00:13  jihite  阅读(968)  评论(0编辑  收藏  举报