C++如何做字符串分割(5种方法)

C++如何做字符串分割(5种方法)1、用strtok函数进行字符串分割原型:char*strtok(char*str,constchar*delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include<string.h>#include<stdio.h&

大家好,又见面了,我是你们的朋友全栈君。

1、用strtok函数进行字符串分割

原型: char *strtok(char *str, const char *delim);

功能:分解字符串为一组字符串。

参数说明:str为要分解的字符串,delim为分隔符字符串。

返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。

其它:strtok函数线程不安全,可以使用strtok_r替代。

示例:

//借助strtok实现split
#include <string.h>
#include <stdio.h>
 
int main()
{ 
   
    char s[] = "Golden Global View,disk * desk";
    const char *d = " ,*";
    char *p;
    p = strtok(s,d);
    while(p)
    { 
   
        printf("%s\n",p);
        p=strtok(NULL,d);
    }
 
    return 0;
}

2、substr函数

原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串

#include <iostream>
#include <string>
#include <vector>
//字符串分割函数
std::vector<std::string> split(std::string str, std::string pattern)
{ 
   
    std::string::size_type pos;
    std::vector<std::string> result;
    str += pattern;//扩展字符串以方便操作
    int size = str.size();
    for (int i = 0; i < size; i++)
    { 
   
        pos = str.find(pattern, i);
        if (pos < size)
        { 
   
            std::string s = str.substr(i, pos - i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    return result;
}

示例:

int main()

{ 
   
  std::string str;
  std::cout<<"Please input str:"<<std::endl;
  //std::cin>>str;
  getline(std::cin,str);
  std::string pattern;
  std::cout<<"Please input pattern:"<<std::endl;
  //std::cin>>pattern;
  getline(std::cin,pattern);//用于获取含空格的字符串
  std::vector<std::string> result=split(str,pattern);
  std::cout<<"The result:"<<std::endl;
  for(int i=0; i<result.size(); i++)
  { 
   
    std::cout<<result[i]<<std::endl;
  }
 
  std::cin.get();
  std::cin.get();
  return 0;
}

3、find_first_not_of

#include<string>
#include<vector>
#include<iostream>
using namespace std;

void Tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{ 
   
  // Skip delimiters at beginning.
  string::size_type lastPos = str.find_first_not_of(delimiters, 0);
  // Find first "non-delimiter".
  string::size_type pos     = str.find_first_of(delimiters, lastPos);
  while (string::npos != pos || string::npos != lastPos)
  { 
   
    // Found a token, add it to the vector.
    tokens.push_back(str.substr(lastPos, pos - lastPos));
    // Skip delimiters. Note the "not_of"
    lastPos = str.find_first_not_of(delimiters, pos);
    // Find next "non-delimiter"
    pos = str.find_first_of(delimiters, lastPos);
  }
}

int main(int argc, char *argv[])
{ 
   
  string str("====aaa==bbb=ccc=ddd====");
  vector<string>tokens;
  Tokenize(str, tokens, "=");
  for( int i = 0; i < tokens.size() ; i++ )
  { 
   
    cout << tokens[i] << endl;
  }
  return 0;
}

4、用Boost进行字符串的分割

用boost库的正则表达式实现字符串分割

#include <iostream>
#include <cassert>
#include <vector>
#include <string>
#include "boost/regex.hpp"
 
std::vector<std::string> split(std::string str,std::string s)
{ 
   
    boost::regex reg(s.c_str());
    std::vector<std::string> vec;
    boost::sregex_token_iterator it(str.begin(),str.end(),reg,-1);
    boost::sregex_token_iterator end;
    while(it!=end)
    { 
   
        vec.push_back(*it++);
    }
    return vec;
}

int main()
{ 
   
    std::string str,s;
    str="sss/ddd/ggg/hh";
    s="/";
    std::vector<std::string> vec=split(str,s);
    for(int i=0,size=vec.size();i<size;i++)
    { 
   
        std::cout<<vec[i]<<std::endl;
    }
    std::cin.get();
    std::cin.get();
    return 0;
}

5、最近发现boost里面有自带的split的函数

如果用boost的话,还是直接用split的好,代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace std;

int main()
{ 
   
  string s = "sss/ddd,ggg";
  vector<string> vStr;
  boost::split( vStr, s, boost::is_any_of( ",/" ), boost::token_compress_on );
  for( vector<string>::iterator it = vStr.begin(); it != vStr.end(); ++ it )
  { 
   
    cout << *it << endl;
  }
  return 0;
}

转载自:
https://www.cnblogs.com/happykoukou/p/5427268.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/130601.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • vb.net listview_不VB思考VB数据表

    vb.net listview_不VB思考VB数据表控件:TEXTBOX   :1个     Name:txtJobNoBUTTON:    2个      Name:btnFilter,btnShowAllLISTVIEW: 1个      Name:lstvwJobNo Columns:JobNo,ContainerID,CartonID,PO,Style,Color,Size,ShipMent,Factory        

    2022年9月1日
    5
  • 目前还存活的多个电驴下载站点!电驴达人收藏[通俗易懂]

    目前还存活的多个电驴下载站点!电驴达人收藏[通俗易懂]目前还存活的多个电驴下载站点!电驴达人收藏(2011更新) 0、http://www.emule-project.net/这个不用说了,emule官方,没有它就没有下面的所有一切,德国人开的。只提供官方版emule软件,没有资源下载。秉承理念“eMule是完全免费的,它也决不包含广告软件、间谍和流氓软件。我们之所以创造eMule是为了快乐和知识,而不…

    2022年7月15日
    56
  • 返回顶部的几种方法总结

    返回顶部的几种方法总结返回顶部的几种方法总结

    2022年7月4日
    25
  • JavaScript算法题整理

    JavaScript算法题整理1.获得两个数相除的商和余数console.log(10/3);//商:3.3333console.log(10%3);//余数:1//获得两个数相除的商和余数console.log(Math.floor(10/3));//13//Math.floor(向下取整)、Math.ceil(向上取整)、round(四舍五入)console.log(0.1+0.2);//在js中,尽量避免做小数点运算//如果有小数位的运算varsum=(0.1*100+0.2*100)/100;c

    2022年6月14日
    35
  • 关于Python中的lambda,这篇阅读量10万+的文章可能是你见过的最完整的讲解[通俗易懂]

    关于Python中的lambda,这篇阅读量10万+的文章可能是你见过的最完整的讲解[通俗易懂]lambda是Python编程语言中使用频率较高的一个关键字。那么,什么是lambda?它有哪些用法?网上的文章汗牛充栋,可是把这个讲透的文章却不多。这里,我们通过阅读各方资料,总结了关于Python中的lambda的“一个语法,三个特性,四个用法,一个争论”。欢迎阅读和沟通(个人微信:slxiaozju)。由于文章是从我的公众号上复制过来的,因此排版不整齐,但是内容绝对充实,欢迎关注公众…

    2022年8月12日
    8
  • 谷歌浏览器驱动器下载网址

    谷歌浏览器驱动器下载网址chrome浏览器驱动下载地址:http://chromedriver.storage.proxy.ustclug.org/index.html

    2022年6月9日
    90

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号