C++中字符串的拆分

strtok()函数

  1. 函数原型: char * strtok(char *s, const char *delim)

  2. 函数功能: 分解字符串为一组字符串,s为要分解的字符串,delim为分隔字符串。
    描述:strtok()用来将字符串分割成一个个片段,参数s指向将要被分隔的字符串,参数delim则为分隔字符串,当strtok()在参数s的字符串中发现到参数delim的分隔字符时,则会将该字符改为'\0'字符,在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL.每次调用成功则返回被分隔片段的指针。

  3. 代码:

#include <iostream>
#include <fstream>           //C++读写文件的头文件
#include <cstring>

using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
    char buffer[256];
    ifstream ifs;
    ifs.open("phone.txt", ios::in);
    if(!ifs.is_open())
    {
        cout << "文件打开失败!" << endl;
        return 0;   
    } 
    while(!ifs.eof())        //判断文是否到达文件末尾,如果到达文件尾返回非0值 
    {
        ifs.getline(buffer, 100);
        cout << buffer << endl;
        char *tokenPrt = strtok(buffer, " ");
        while(tokenPrt != NULL)
        {
            cout << tokenPrt << endl;
            tokenPrt = strtok(NULL, " ");   
        }   
    }
    ifs.close();
    return 0;
}
效果图.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。