当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++常用的string字符串截断函数

C++常用的string字符串截断函数

2019年07月19日  | 移动技术网IT编程  | 我要评论

日搜,20121115新闻联播,供销e家休闲农业

c++中经常会用到标准库函数库(stl)的string字符串类,跟其他语言的字符串类相比有所缺陷。这里就分享下我经常用到的两个字符串截断函数:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

//根据字符切分string,兼容最前最后存在字符
void cutstring(string line, vector<string> &subline, char a)
{
    //首字母为a,剔除首字母
    if (line.size() < 1)
    {
        return;
    }
    if (line[0] == a)
    {
        line.erase(0, 1);
    }

    size_t pos = 0;
    while (pos < line.length())
    {
        size_t curpos = pos;
        pos = line.find(a, curpos);
        if (pos == string::npos)
        {
            pos = line.length();
        }
        subline.push_back(line.substr(curpos, pos - curpos));
        pos++;
    }

    return;
}

//根据空截断字符串
void chopstringlineex(string line, vector<string> &substring)
{
    stringstream linestream(line);
    string sub;

    while (linestream >> sub)
    {
        substring.push_back(sub);
    }
}

int main()
{
    string line = ",abc,def,ghi,jkl,mno,";
    vector<string> subline;
    char a = ',';
    cutstring(line, subline, a);
    cout << subline.size()<<endl;
    for (auto it : subline)
    {
        cout << it << endl;
    }

    cout << "-----------------------------" << endl;

    line = "   abc   def   ghi  jkl  mno ";
    subline.clear();    
    chopstringlineex(line, subline);
    cout << subline.size() << endl;
    for (auto it : subline)
    {
        cout << it << endl;
    }


    return 0;
}

函数cutstring根据选定的字符切分string,兼容最前最后存在字符;函数chopstringlineex根据空截断字符串。这两个函数在很多时候都是很实用的,例如在读取文本的时候,通过getline按行读取,再用这两个函数分解成想要的子串。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网