std::string 字符串操作(分割,去空格)

本文介绍了一种在C++中实现字符串分割的方法,并提供了一个去除字符串前后空格的实用函数。通过具体的代码实现,读者可以了解到如何高效地处理字符串,这对于日常编程工作非常有用。

很多情况下我们需要对字符串进行分割,如:“a,b,c,d”,以‘,’为分隔符进行分割:

stringex.h

#ifndef _STRING_EX_H
#define _STRING_EX_H

#include <string>
#include <vector>

// 字符串分割
int StringSplit(std::vector<std::string>& dst, const std::string& src, const std::string& separator);

// 去掉前后空格
std::string& StringTrim(std::string &str);

#endif

stringex.cpp

#include "stringex.h"

int StringSplit(std::vector<std::string>& dst, const std::string& src, const std::string& separator)
{
    if (src.empty() || separator.empty())
        return 0;

    int nCount = 0;
    std::string temp;
    size_t pos = 0, offset = 0;

    // 分割第1~n-1个
    while((pos = src.find_first_of(separator, offset)) != std::string::npos)
    {
        temp = src.substr(offset, pos - offset);
        if (temp.length() > 0){
            dst.push_back(temp);
            nCount ++;
        }
        offset = pos + 1;
    }

    // 分割第n个
    temp = src.substr(offset, src.length() - offset);
    if (temp.length() > 0){
        dst.push_back(temp);
        nCount ++;
    }

    return nCount;
}

std::string& StringTrim(std::string &str)
{
    if (str.empty()){
        return str;
    }
    str.erase(0, str.find_first_not_of(" "));
    str.erase(str.find_last_not_of(" ") + 1);
    return str;
}

 

转载于:https://www.cnblogs.com/ziyu-trip/p/6875658.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值