「分享與快樂同在!」
最近有小夥伴詢問如何按指定分隔符分割字串,在karel中並沒有按字元分割的內建程式供我們使用,那麼我們就來實現這個功能!
在專案中,經常會在字串中提取資料,比如機械人與相機使用tcp/ip通訊、字串文字中資料提取等等。如何按字元將乙個字串資料拆分為多個字串,最終將字串轉換為其他資料型別?
實現**:
注:在**中並未將字串轉為real資料型別,那只是呼叫一下內建函式。
program str_cut1%stacksize = 4000%include ../0_lib/libtypevar plist:prmtype --引數存放位置 count,i,prmcount:integer --字串分割後存放位置,根據實際需求設定陣列、字串長度。 strlist:array[30] of string[30] --字串剪下分割 routine str_split(source,split:string;strarray:array of string):integer from libroutine --獲取引數函式 routine getprm(count:integer;valuetype:array of integer;intvalue:array of integer;realvalue:array of real;str:array of string;statevalue:array of integer):integer from libroutine begin --獲取引數 prmcount = getprm(plist.count , plist.valuetype , plist.intvalue , plist.realvalue , plist.str , plist.statusvalue) --判斷引數1、2 均為字串 if((prmcount =2) and ( plist.valuetype[1] = strtype ) and ( plist.valuetype[2] = strtype ) ) then --按引數2字串,分割引數1字串,結果存放在 strlist陣列中 count = str_split(plist.str[1],plist.str[2],strlist) --列印分割後,字串段數 write(cr,'total:',count,cr) --遍歷列印字串 for i=1 to count do write(' [',strlist[i],'] ') endfor endif --end--end str_cut1
程式中,引用了libroutine檔案中的 str_split函式來實現字串分割。
str_split函式有3個引數:
source:需要被分割的字串。
split: 分割符號
strarray:分割後的字串
返回值:字串被分割後的段數,如果沒有分割,也將返回1。
libroutine 檔案中 str_split函式實現**:
--按字元分割字串--source:被分割字串--split:分割符,支援多個字元--strarray:分割後的單個字串陣列routine str_split(source,split:string;strarray:array of string):integervar count,i:integer splitlen:integer sourcelen:integer readpos:integer splitindex:integer strtemp:string[254] maxcount:integerbegin count =0 splitindex = 0 readpos = 1 splitlen = str_len(split) sourcelen = str_len(source) maxcount = array_len(strarray) if (splitlen = 0) or (sourcelen = 0) then return (0) endif for i = 1 to maxcount do --複製源字串 strtemp = sub_str(source,readpos,sourcelen) --查詢分隔符位置 splitindex = index(strtemp,split) count=count+1 if splitindex > 0 then readpos = readpos + splitindex+splitlen-1 --剪下字串 strarray[count] = sub_str(strtemp,1,splitindex-1) else strarray[count] = strtemp return (count) endif --判斷越界 if readpos > sourcelen then return (count) endif endfor return (count) end str_split
ok!今天的分享到此結束,記得分享哦!
mysql分割字串 mysql分割字串
專案有通過一批id去過濾結果的需求,因為這個id是從其他平台拉下來的excel,為了避免加引號逗號的麻煩,在mysql儲存過程裡面拼接。在此做個記錄。很多地方用得上。1.通過某個字元,分割字串的函式。輸入分別為f string 待分割字串 f delimiter 分割字元 f order 取的字串的...
分割字串
string.split char 返回包含此例項中的子字串 由指定 char 陣列的元素分隔 的 string 陣列。由 net compact framework 支援。string.split char,int32 返回包含此例項中的子字串 由指定 char 陣列的元素分隔 的 string ...
分割字串
最近手裡的活用到分割字串,自己嘗試寫了乙個,在網上找到幾個,留著以後備用。char steps char token char strusbinfo 512 memcpy strusbinfo,1e 2f 3g strlen 1e 2f 3g token strtok strusbinfo,step...