1. 程式人生 > >C語言實現按分隔符來擷取字串

C語言實現按分隔符來擷取字串

問題描述:我們的系統通過Socket網路通訊往linux伺服器上傳送資料,伺服器上接收的資料格式是以逗號隔開的字串。我們需要將這個字串按逗號作為分隔符來擷取。

解決方法:使用C語言中的strtok()函式實現

程式碼實現(下面程式碼的功能是將字串"now , is the time for all , good men to come to the , aid of their country"以逗號作為分隔符來擷取,並將截取出的字串打印出來):

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "now , is the time for all , good men to come to the , aid of their country";
    char delims[] = ",";
    char *result = NULL;
    result = strtok( str, delims );
    while( result != NULL ) {
    printf( "result is \"%s\"\n", result );
    result = strtok( NULL, delims );
    }
}
執行結果如下:



進一步:封裝成實現按分隔符擷取字串的函式

#include <stdio.h>  
#include <string.h>  
void split(char str[],char delims[])
{
    char *result = NULL; 
    result = strtok( str, delims );  
    while( result != NULL ) {  
    printf( "result is \"%s\"\n", result );  
    result = strtok( NULL, delims );  
    }  
}
int main()  
{  
    char str[] = "now , is the time for all , good men to come to the , aid of their country";  
    char delims[] = ",";  
	split(str,delims);
}