C++中字符串的拆分

strtok()函數(shù)

  1. 函數(shù)原型: char * strtok(char *s, const char *delim)

  2. 函數(shù)功能: 分解字符串為一組字符串,s為要分解的字符串,delim為分隔字符串。
    描述:strtok()用來將字符串分割成一個個片段,參數(shù)s指向?qū)⒁环指舻淖址瑓?shù)delim則為分隔字符串,當(dāng)strtok()在參數(shù)s的字符串中發(fā)現(xiàn)到參數(shù)delim的分隔字符時,則會將該字符改為'\0'字符,在第一次調(diào)用時,strtok()必需給予參數(shù)s字符串,往后的調(diào)用則將參數(shù)s設(shè)置成NULL.每次調(diào)用成功則返回被分隔片段的指針。

  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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容