[python按空格分割字符串]用C++实现python字符串分割函数 split()与rsplit()实例

更新时间:2020-01-24    来源:python    手机版     字体:

【www.bbyears.com--python】

本文我们将实现两个python字符串分割函数。这两个函数的函数原型为:

split(spe = None,maxsplit= -1)
rsplit(spe= None ,maxsplit = -1)

这两个方法使用参数spe作为分隔符,将字符串切割成指定的maxsplit段,并以列表的形式返回切割后的字符串。默认的分隔符是空格,默认情况下对所有的分隔符进行分割:

>>>
>>> s = "I'm not to see you"
>>> s.split()
["I'm", 'not', 'to', 'see', 'you']
>>>

>>> s.rsplit()
["I'm", 'not', 'to', 'see', 'you']
>>>

可以看到字符串根据空格进行分割,分割成的各段作为列表的元素组成了列表并返回。
我们再来看更多的例子:


分隔成指定段数

>>>
>>> s = 'aaaaaaaaaaa'
>>> s.split('a',2) #依据'a'进行分割,最大分割数为2(分割两次)
['', '', 'aaaaaaaaa']
>>>

>>>
>>> s.split('a',1000)#分隔数偏多
['', '', '', '', '', '', '', '', '', '', '', '']
>>>

>>>
>>> s.split('a',-19)#分割数为负数
['', '', '', '', '', '', '', '', '', '', '', '']
>>>

split方法从左至右处理字符串,而rsplit方法从右至左处理字符串:

>>> ##两个方法的区别
>>> s
'aaaaaaaaaaa'
>>> s.split('a',2)
['', '', 'aaaaaaaaa']
>>> s.rsplit('a',2)
['aaaaaaaaa', '', '']
>>>

C++实现

我们使用容器vector来保存字符串分割后的元素。尽管我们的目标是实现split与rsplit这两个函数,但是模块化的思想促使我们定义出以下这5个函数:

reverse_strings :用于rsplit_whitepace与rsplit函数。

split_whitespace :用于split调用,以空格作为分隔符对整个字符串做分隔处理(默认)

rsplit_whitespace :用于 rsplit调用,以空格作为分隔符对整个字符串做分隔处理(默认)

split 我们所期待的函数

rsplit 我们所期待的函数

在函数的实现中,我们会调用到C++容器提供的一些接口:vector容器的push_back,substr等。


头文件与宏定义

在这两个函数的实现中,我们需要如下头文件与宏定义:

#include
#include
#define MAX_32BIT_INT 2147483467

倒序函数reverse_strings

这个函数提供给rsplit函数使用。具体使用继续向下看。

python;toolbar:false\">//采用std的swap函数
void reverse_strings(std::vector< std::string > & result)
{
    for (std::vector< std::string >::size_type i = 0; i < result.size() / 2; i++)
    {
        std::swap(result[i], result[result.size() - 1 - i]);
    }
}


spilt()方法默认情况下处理函数:split_whitespace

void split_whitespace(const std::string &str, std::vector &result, int maxsplit)
{
    std::string::size_type i, j, len = str.size();
    for (i = j = 0; i < len;)
    {
        
        while (i < len&&::isspace(str[i]))
            i++;
        j = i;
    
        while (i < len&&!::isspace(str[i]))
            i++;
        if (j < i)
        {
            if (maxsplit-- <= 0)
                break;
            result.push_back(str.substr(j, i - j));
            while (i < len&&::isspace(str[i]))
                i++;
            j = i;
        }
    }
    if (j < len)
    {
        result.push_back(str.substr(j, len - j));
    }
}


split()函数

void split(const std::string &str, std::vector&result, const std::string &sep, int maxslit)
{
    result.clear();
    if (maxslit < 0)
        maxslit = MAX_32BIT_INT; //MAX_32BIT_INT是自己定义的一个整数,当maxslit为负数时,对整个字符串做切割处理
    //split函数默认为空格为分隔符
    if (sep.size() == 0)
    {
        //调用函数进行空格切割
        split_whitespace(str, result, maxslit);
        return;
    }
    std::string::size_type i, j, len = str.size(), n = sep.size();
    i = j = 0;
    while (i + n <= len)
    {
        if (str[i] == sep[0] && str.substr(i, n)== sep)
        {
            if (maxslit-- <= 0)
                break;
            result.push_back(str.substr(j, i - j));
            i = j = i + n;
        }
        else
            i++;
    }
    //剩下部分
    result.push_back(str.substr(j, len - j));
}


rsplit()方法默认情况处理函数

void rsplit_whitespace(const std::string &str, std::vector&result, int maxsplit)
{
    std::string::size_type i,j,len = str.size();
    for (i = j = len; i > 0;)
    {
        while (i > 0 && ::isspace(str[i - 1]))
            i--;
        j = i;
        while (i > 0 && !::isspace(str[i - 1]))
            i--;
        if (j > i)
        {
            if (maxsplit-- <= 0)
                break;
            result.push_back(str.substr(i, j - i));
            while (i > 0 && ::isspace(str[i - 1]))
                i--;
            j = i;
        }
    }
    if (j > 0)
    {
        result.push_back(str.substr(0, j));
    }
    reverse_strings(result);
    
}


rsplit()函数

void rsplit(const std::string &str, std::vector&result, const std::string &sep, int maxsplit)
{
    if (maxsplit < 0)
    {
        split(str, result, sep, maxsplit);
        return;
    }
    result.clear();
    if (sep.size() == 0)
    {
        rsplit_whitespace(str, result, maxsplit);
        return;
    }
    std::string::size_type i, j;
    std::string::size_type len = str.size();
    std::string::size_type n = sep.size();
    i = j = len;
    while (i >= n)
    {
        if (str[i - 1] == sep[n - 1] && str.substr(i - 1, n) == sep)
        {
            if (maxsplit-- <= 0)
                break;
            result.push_back(str.substr(i, n));
            i = j = i - n;
        }
        else
        {
            i--;
        }
    }
    result.push_back(str.substr(0, j));
    reverse_strings(result);
}


测试

string s = "I'm not to see you";
vector result;
string sep = " ";
split(s,result,sep,10);


结果:

string  b = "abc abc abc abc";
vectorresult;
string sep = "a";
split(b, result, sep, 2);
for (int i = 0; i < result.size(); i++)
    cout << result[i] << endl;


结果:

string  b = "abc abc abc abc";
vectorresult;
string sep = "a";
rsplit(b, result, sep, 2);
for (int i = 0; i < result.size(); i++)
    cout << result[i] << endl;


结果:


感谢耐心看完,如果有错误的地方,恳请指出。希望喜欢C++与python的同学多交流。




读取文件行并分割行中字符串:C/C++以及python实现

一、问题描述

给定一文件,依次读取文件中各行的字符串(字符串之间以空格分开)。

例如:文件test.txt中有如下内容:

first  second  third  forth  (第一行)

fifth  sixth seventh   (第二上)

... (其他行)

则读取的内容依次为:   first  second  third  forth   fifth  sixth seventh


二、解题步骤


(1)首先读取文件各行

(2)然后针对每行依次读取各个字符串

(3)最后将读取的字符串依次存入内存中


三、编程实现

1、C语言实现

C语言中,有个函数:strtok() 用于分割字符串,其原型如下:

#include  
char* strtok(char str[], const char* delim);  

说明:

I、参数:str为待分割的字符串;delim为分隔符字符串。

II、用法:该函数的使用比较奇特,若在str字符串中发现参数delim中的分割字符串之字符时,则会将该字符修改为‘\0’字符(字符串结束符)。在第一次调用时,strtok()必须给予参数str字符串,下次调用时则须将str设置成NULL。每次调用成功则返回指向被分割出片段的指针。

例子:

#include   
#include   
int main()  
{  
    char s[] ="ab|cdef;ghi|jkl";  
    char* delim = "|;";  
    char* tmp;  
    tmp = strtok(s, delim);  
    while(tmp != NULL)  
    {     
        printf("%s\\n",tmp);  
        tmp = strtok(NULL, delim);    
    }  
  
    return 0;  
}


输出:


下面给出读文件各行中的字符串,并将其保存于内存中。设文件名为:test.txt,其内容如下:


对应的程序为:

#include   
#include   
  
/* 
@in, str: 待分割的字符串 
@in, delim: 分隔符字符串 
@in_out, dest: 保存分割后的每个字符串,设为char**的引用,即表示可修改其值 
@out, pCount: 记录一行中分割所得字符串的个数 
*/  
void split(char* str, char* delim, char** &dest, int* pCount)  
{  
    char* tmp;  
    *pCount=0;  
    if(NULL ==  str || 0 == strlen(str)) return ;  
    if(NULL == delim || 0 == strlen(delim)) return ;  
  
    tmp = strtok(str, delim);  
    while(tmp != NULL)  
    {     
        for(int j =0; tmp[j]!='\\0';j++)  
        {  
            if(tmp[j]=='\\n')break; //到达行末  
            (*dest)[j] = tmp[j];  
        }  
        (*dest)[j]='\\0';  
        dest++;   
        (*pCount)++;  
  
        tmp = strtok(NULL, delim);  
    }  
}  
int main()  
{  
  
    FILE* fp;  
    char lineBuf[129];  
    char* delim = " ";  //分隔符为:空格  
    int num = 0;    //文件中总的字符串个数  
    int count = 0;  //一行中的字符串个数  
    int i;  
  
    /*申请内存用于存放字符串*/  
    char** dest  = new char*[128];  
    for( i = 0; i < 128; i++)  
    {  
        dest[i] = new char[64];  
    }  
  
    char** tmpDest = dest;  
    if(fp=fopen("test.txt", "r"))  
    {     
        while(fgets(lineBuf, 128, fp) != NULL)  
        {  
            split(lineBuf, delim, tmpDest, &count);  
            num  = num + count;  
        }  
    }  
    fclose(fp);  
  
    for(i= 0; i < num; i++)  
    {  
        printf("%s\\n",dest[i]);  
    }  
  
    /*释放内存*/  
    for(i = 0; i<128;i++)  
    {  
        delete []dest[i];  
    }  
    delete[]dest;  
  
    return 0;  
}


2、C++语言实现

C++中没有实现split功能的函数,下面用C++ STL中的一些函数模拟实现split功能。

#include <iostream>  
#include   
#include   
#include   
using namespace std;  
  
/* 
@in, src: 待分割的字符串 
@in, delim: 分隔符字符串 
@in_out, dest: 保存分割后的每个字符串 
*/  
void split(const string& src, const string& delim, vector& dest)  
{  
    string str = src;  
    string::size_type start = 0, index;  
    string substr;  
  
    index = str.find_first_of(delim, start);    //在str中查找(起始:start) delim的任意字符的第一次出现的位置  
    while(index != string::npos)  
    {  
        substr = str.substr(start, index-start);  
        dest.push_back(substr);  
        start = str.find_first_not_of(delim, index);    //在str中查找(起始:index) 第一个不属于delim的字符出现的位置  
        if(start == string::npos) return;  
  
        index = str.find_first_of(delim, start);  
    }  
}  
  
  
int main()  
{  
    ifstream infile("test.txt", ios::in);  
    vector results;  
    string word;  
    string delim(" ");  
    string textline;  
    if(infile.good())  
    {  
        while(!infile.fail())  
        {  
            getline(infile, textline);  
            split(textline, delim, results);  
        }  
    }  
    infile.close();  
  
    vector::iterator iter = results.begin();  
    while(iter != results.end())  
    {  
        cout<<*iter++<


3、Python语言的实现

在Python中有专门的函数split()对字符串进行分割,实现较为简单

myfile = open('test.txt', 'r')  
allWords = []  
line = myfile.readline()  
while line:  
    list = line.split(' ')  
    for word in list:  
        if word[-1]=='\\n':  
            allWords.append(word[:-1])  #去掉行末的'\\n'  
        else:  
            allWords.append(word)  
    line = myfile.readline()  
myfile.close()    
print allWords  
References:


本文来源:http://www.bbyears.com/jiaocheng/84818.html

热门标签

更多>>

本类排行