您的位置:首页 > 编程语言 > C语言/C++

c++ 字符串分割一、用strtok函数进行字符串分割 原型: char *strtok(char *str, const char *delim); 功能:分解字符串为一组字符串。 参数说明:

2013-10-28 11:26 821 查看
一、用strtok函数进行字符串分割

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

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

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

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

#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;
 }


二、用STL进行字符串的分割

涉及到string类的两个函数find和substr:

1、find函数

原型:size_t find ( const string& str, size_t pos = 0 ) const;

功能:查找子字符串第一次出现的位置。

参数说明:str为子字符串,pos为初始查找位置。

返回值:找到的话返回第一次出现的位置,否则返回string::npos

2、substr函数

原型:string substr ( size_t pos = 0, size_t n = npos ) const;

功能:获得子字符串。

参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
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;
 }


返回值:子字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐