C語(yǔ)言根據(jù)協(xié)議分割獲取字符串單元的實(shí)現(xiàn)代碼
協(xié)議做如下規(guī)定:
規(guī)定數(shù)據(jù)協(xié)議:
序列號(hào) 長(zhǎng)度 狀態(tài)字 數(shù)據(jù)長(zhǎng)度 數(shù)據(jù)1 數(shù)據(jù)2 數(shù)據(jù)3
以空格作為數(shù)據(jù)單元。
ep:
00001 00007 1 3 34567 26358 32698 (1) (2) (3)(4) (5) (6) (7)
如ep所示:
(1)00001就是數(shù)字1,即代表序列號(hào)為1 (2)00007就是數(shù)字7,即代表長(zhǎng)度為7 (3)1代表狀態(tài)字 (4)3代表數(shù)字長(zhǎng)度 (5)34567代表數(shù)據(jù)1 (6)26358代表數(shù)據(jù)2 (7)32698代表數(shù)據(jù)3
這樣就找到規(guī)律了,假設(shè)數(shù)據(jù)都為整型或者負(fù)整型,我們就可以來(lái)實(shí)現(xiàn)以下代碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> //根據(jù)空格拆分字符串 int partition(char *src, char *par, int pos) { int i,j; i = pos; //取得一個(gè)非空字符 while(src[i] == ' ') ++i; if(src[i] != '\0') { j = 0; while((src[i] != '\0') && (src[i] != ' ')) { //判斷條件是否滿足 if((src[i] > '9') || (src[i] < '0') && (src[i] != '-')) return -1 ; par[j] = src[i]; ++i; ++j; } par[j]='\0'; return i; } else return -1; } int main(void) { int serial_number ; int lenght ; int status ; int data_length; int data1,data2,data3; int position = 0; int para_flag = 1 ; int parameter_item = 0; char partition_string[20] = {0}; char *data = "00001 00007 1 3 34567 26358 32698"; while(para_flag) { if(para_flag == 0) break ; if((position = partition(data,partition_string,position)) != -1) { ++parameter_item ; switch(parameter_item) { case 1: serial_number = atoi(partition_string); break ; case 2: lenght = atoi(partition_string); break ; case 3: status = atoi(partition_string); break ; case 4: data_length = atoi(partition_string); break ; case 5: data1 = atoi(partition_string); break ; case 6: data2 = atoi(partition_string); break ; case 7: data3 = atoi(partition_string); para_flag = 0 ; break ; } } } printf("序號(hào):%d\n",serial_number); printf("長(zhǎng)度:%d\n",lenght); printf("狀態(tài)字:%d\n",status); printf("數(shù)據(jù)長(zhǎng)度:%d\n",data_length); printf("數(shù)據(jù)1:%d\n",data1); printf("數(shù)據(jù)2:%d\n",data2); printf("數(shù)據(jù)3:%d\n",data3); return 0; }
運(yùn)行結(jié)果:
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
C++實(shí)現(xiàn)簡(jiǎn)單的圖書管理系統(tǒng)
本文給大家分享的是使用C++實(shí)現(xiàn)簡(jiǎn)單的圖書管理系統(tǒng)的代碼,本系統(tǒng)采用了面向?qū)ο蟮某绦蛟O(shè)計(jì)方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-08-08C++中double浮點(diǎn)數(shù)精度丟失的深入分析
這篇文章主要給大家介紹了關(guān)于C++中double浮點(diǎn)數(shù)精度丟失的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01C++11, 14, 17對(duì)tuple元素的訪問(wèn)詳情
這篇文章主要介紹了C++11, 14, 17對(duì)tuple元素的訪問(wèn)詳情,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11C語(yǔ)言求解無(wú)向圖頂點(diǎn)之間的所有最短路徑
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言求解無(wú)向圖頂點(diǎn)之間的所有最短路徑,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01C語(yǔ)言棧順序結(jié)構(gòu)實(shí)現(xiàn)代碼
一個(gè)能夠自動(dòng)擴(kuò)容的順序結(jié)構(gòu)的棧 ArrStack 實(shí)例 (GCC編譯),有需要的朋友可以參考一下2013-10-10