1. 程式人生 > >C語言實現split以某個字元分割一個字串

C語言實現split以某個字元分割一個字串

方式一:
使用strtok

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

void split(char *src,const char *separator,char **dest,int *num) {
	/*
		src 源字串的首地址(buf的地址) 
		separator 指定的分割字元
		dest 接收子字串的陣列
		num 分割後子字串的個數
	*/
     char *pNext;
     int count = 0;
     if (src == NULL || strlen(src) == 0
) //如果傳入的地址為空或長度為0,直接終止 return; if (separator == NULL || strlen(separator) == 0) //如未指定分割的字串,直接終止 return; pNext = (char *)strtok(src,separator); //必須使用(char *)進行強制型別轉換(雖然不寫有的編譯器中不會出現指標錯誤) while(pNext != NULL) { *dest++ = pNext; ++count; pNext = (
char *)strtok(NULL,separator); //必須使用(char *)進行強制型別轉換 } *num = count; } int main(){ int i; char buf[]="www.baidu.com,www.taobao.com,www.csdn.com,www.python.org"; //用來接收返回資料的陣列。這裡的陣列元素只要設定的比分割後的子字串個數大就好了。 char *revbuf[8] = {0}; //存放分割後的子字串 //分割後子字串的個數 int num = 0; split(buf,",",revbuf,
&num); //呼叫函式進行分割 //輸出返回的每個內容 for(i = 0;i < num; i ++) { //lr_output_message("%s\n",revbuf[i]); printf("%s\n",revbuf[i]); } return 0; } Dev c++中執行結果: www.baidu.com www.taobao.com www.csdn.com www.python.org

方式二:
使用strchr
檢視另一篇文章