C++ string 相关操作总结

一、用C++分隔字符串

我们都知道,Shell中的awk用来处理字符串十分方便,可在C++中就没有那么容易了。有这样一个需求:
假设文本内容如下所示:

zhangsan | 3456123, hunan
lisi, 4564234 | hubei
wangwu, 4433253,beijing
我们需要以"|" ","为分隔符,同时又要过滤空格,把每行分成相应的字段进行输出。
C++中的string中有find,find_first_of,find_first_not_of等函数,用来处理字符串是再合适不过了。下面是具体的代码:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>
#include<functional>
#include<fstream>
#include<cassert>
using namespace std;
int main()
{
    ifstream fin("D:\\data.txt");
    if (!fin)
    {
        cout << "Open file error!" << endl;
        return -1;
    }
    string str;
    string strset = "|, ";
    int pos = 0;
    while (getline(fin, str))
    {
        cout << "------------------------" << endl;
        cout << str << endl;
        cout << "after processed:" << endl;
        int first(0);
        while ((first=str.find_first_not_of(strset,first)) != string::npos)
        {
            int last = str.find_first_of(strset,first);
            if (last == string::npos)
            {
                cout << str.substr(first) << endl;
                break;
            }
            cout << str.substr(first, last - first )<<endl;
            first = last+1;
        }
        pos = 0;
        cout << endl;
    }
    fin.close();
    system("pause");
	return 0;
}

2.用C++ string 替换字符串
C++ string中字符串替换函数replace的原型只提供了按位置或区间的操作,而不能实现用一个字符串替换另一个字符串的功能。这个简单,自己写一个替换函数呗。

void string_replace(string& str, const string& strsrc, const string& strdst)
{
    if (str.size == 0)
        cerr << "invalid string!" << endl;
    string::size_type pos = 0;
    string::size_type strsrclen = strsrc.size();
    string::size_type strdstlen = strdst.size();
    while ((pos = str.find(strsrc, pos) )!= string::npos)
    {
        str.replace(pos, strsrclen, strdst);
        pos += strdstlen;
    }
}

主函数如下:

int main()
{
    string str = "2014,ustc! ustc is the university where my friend had studied!";
    cout << str << endl;
    cout << "after replace,the string is :" << endl;
    string_replace(str,"ustc","zju");
    cout << str << endl;
    system("pause");
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值