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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • 图解Linux命令之–dos2unix命令

    图解Linux命令之–dos2unix命令dos2unix命令–&gt;DostoUNIX的缩写,用来将DOS格式的文本文件转换为UNIX格式find.-typef-execdos2unix{}\;find.-typef|xargs|dos2unix备注:1)为什么需要用dos2unix进行格式转换在Linux系统下经常会出现下列提示:/bin/sh^M:badinter…

    2022年7月14日
  • textmate 快捷技巧

    textmate 快捷技巧textmate快捷技巧文章分类:综合技术高手都是可以不用鼠标的,恩,向高手学习.textmate的快捷键忒多了:自动补全:esc查找项目文件:command+t查找文件内符号:shift+command+t跳到某行:command+l选择:shift+方向键向后缩进:option+tab向前缩进:shift+option+tabreformat所选:option+command+[大写所选:control+u小写所选:

    2022年7月15日
  • c语言和vc的区别_c++是c语言的升级版吗

    c语言和vc的区别_c++是c语言的升级版吗returnx+y}fnsub(x,yint)int{returnx-y}就像在Go和C中一样,函数不能重载。这简化了代码并提高了可维护性和可读性。函数可以在声明之前使用:add和sub在main之后声明,但仍然可以从main调用。对于V中的所有声明都是如此,并且不需要头文件或考虑文件和声明的顺序。V的目标之一是向具有不同编译器开发经验的开发人员开放。作者希望编译器不再是让人捉摸不透、只…

    2022年8月12日
  • 一致性哈希 哈希槽(哈希碰撞和哈希冲突)

    背景随着memcache和redis的出现,更多人认识到了一致性哈希。一致性哈希用于解决分布式缓存系统中的数据选择节点存储问题和数据选择节点读取问题以及在增删节点后减少数据缓存的消失范畴,防止雪崩的发生。哈希槽是在rediscluster集群方案中采用的,rediscluster集群没有采用一致性哈希方案,而是采用数据分片中的哈希槽来进行数据存储与读取的。一致性哈希一致性hash是一个0-2^32的闭合圆,(拥有2^23个桶空间,每个桶里面可以存储很多数据,可以理解为s3的存储桶)所

    2022年4月14日
  • RS485接口定义

    RS485接口定义

    1.英式标识为 TDA(-) 、TDB(+) 、RDA(-) 、RDB(+) 、GND 
    2.美式标识为 Y 、Z 、 A 、 B 、 GND  
    3.中式标识为 TXD(+)/A 、TXD(-)/B 、RXD(-) 、RXD(+)、GND  
       rs485两线一般定义为:  
                 “A, B”或”Date+,Date-”  
       即常说的:”485+,485-”  
       rs485四线一般定

    2022年5月27日
  • httpd 启动报错“”Permission denied: make_sock: could not bind to address [::]:80“”

    httpd 启动报错“”Permission denied: make_sock: could not bind to address [::]:80“”

    2022年3月12日

发表回复

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

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