码迷,mamicode.com
首页 > 编程语言 > 详细

C++字符串分隔

时间:2017-03-25 15:36:05      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:提取   字符   头文件   char   put   path   blog   code   man   

记录两种C++中的字符串分隔方法。

代码仅作为提供思路参考,不能实际运行。

一、getline

getline函数介绍: 
头文件:#include <string.h>

函数原型:istream& getline (istream& is, string& str, char delim);

函数说明:从is输入流中提取依次字符存存放到str中直到遇到delim字符或者换行符’\n’。

这个方法的缺点是不能直接对字符串进行操作,需要把字符串类型先转换成流,然后进行分隔。当处理的文本较大,行数较多的时候,类型之间的转换时很耗时的,效率不算高。

    string fileContent;
    string strLine;      //保存文本的一行
    string strFileds;    //分隔出来的字段
    string strfileName;
    ifstream inputFile;
strFileName
= "testdata.csv"; inputFile.open(strFileName.c_str()); fileContent << inputFile.rdbuf(); stringstream temString; // using for splitting while (getline(fileContent, strLine)) //reading line { temString << strLine; //类型转换成流 while (getline(temString, strFileds, ,)) { cout << strFileds << " "; } }

二、指针

另一种字符串分隔的方法是通过指针一个一个扫描字符串,当遇到分隔符的时候,就截取出来。效率较上一种方法更高。

    ifstream inputFile;
    long long l_Length;
    char *c_pBuffer; 
    string  filepath = "testdata.csv";
    inputFile.open(filepath.c_str());
    
    if(inputFile.is_open())
    {
        inputFile.seekg(0, ios::end);
        l_Length = inputFile.tellg();
        inputFile.seekg(0, ios::beg);
        c_pBuffer = new char[l_Length];
        inputFile.read(c_pBuffer, l_Length);
    }
    else
    {
        cout << "Cannot open file!\n";
    }
    
    char *c_pHead, *c_pTail;
    c_pHead = c_pTail = c_pBuffer;   

    /* translating the file*/
    while (!inputFile.eof())
    {
        if (*c_pTail == , || *c_pTail == \n )
        {
            c_pTail++;
            string strTemp = string(c_pHead, c_pTail);
            cout << strTemp;
            c_pHead = c_pTail;
        }
        else
        {
            c_pTail++;
        }    
    }        

 

C++字符串分隔

标签:提取   字符   头文件   char   put   path   blog   code   man   

原文地址:http://www.cnblogs.com/philipce/p/6617084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!