#includeiostream
創(chuàng)新互聯(lián)公司專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,德陽機房托管,德陽機房托管,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
#includevector
#includesstream
usingnamespacestd;
intmain()
{
strings;
vectorintv;
cins;
//將讀入的字符串轉(zhuǎn)化成is流
istringstreamis(s);
intinter;
charch;
while(isinter)//只能讀出is流中的一個整形讀進inter
{
v.push_back(inter);
isch;//然后讀一個字符型讀進ch
}
for(inti=0;iv.size();i++)
coutv[i]"";
coutendl;
return0;
}
擴展資料
C語言的字符串按照指定字符串分割操作
#includestdio.h
#pragmawarning(disable:4996)
#includestdlib.h
intmain()
{
charstr[]="我,是,中國,程序員";
char*ptr;
char*p;
printf("開始前:str=%s\n",str);
printf("開始分割:\n");
ptr=strtok(str,",");
while(ptr!=NULL){
printf("ptr=%s\n",ptr);
ptr=strtok(NULL,",");
}
getchar();
}
#include?stdio.h
#include?string.h
//?將str字符以spl分割,存于dst中,并返回子字符串數(shù)量
int?split(char?dst[][80],?char*?str,?const?char*?spl)
{
int?n?=?0;
char?*result?=?NULL;
result?=?strtok(str,?spl);
while(?result?!=?NULL?)
{
strcpy(dst[n++],?result);
result?=?strtok(NULL,?spl);
}
return?n;
}
int?main()
{
char?str[]?=?"what?is?you?name?";
char?dst[10][80];
int?cnt?=?split(dst,?str,?"?");
for?(int?i?=?0;?i??cnt;?i++)
puts(dst[i]);
return?0;
}
不需要專門分割,C語言里面本來就是用字符數(shù)組來保存的,如:char a[20]="Hello world!";這個字符串,char[0]就是H,char[1]就是e。
如果要分割子串,可以使用strtok函數(shù)。
char *strtok(char *s, char *delim);
分解字符串為一組字符串。s為要分解的字符串,delim為分隔符字符串。
首次調(diào)用時,s指向要分解的字符串,之后再次調(diào)用要把s設(shè)成NULL。
strtok在s中查找包含在delim中的字符并用NULL('')來替換,直到找遍整個字符串。
使用strtok函數(shù)即可實現(xiàn)分割字符串。
1、strtok函數(shù):
原型:char *strtok(char s[], const char *delim);
功能:將一個字符串分解為一組字符串,s為要分解的字符串,delim為分隔符字符串;
說明:當strtok函數(shù)在參數(shù)s的字符串中發(fā)現(xiàn)參數(shù)delim中包含的分割字符時,則會將該字符改為\0 字符。在第一次調(diào)用時,strtok()必需給予參數(shù)s字符串,往后的調(diào)用則將參數(shù)s設(shè)置成NULL。每次調(diào)用成功則返回指向被分割出片段的指針;
頭文件:string.h;
返回值:從字符串s開頭開始的一個個被分割的字符串。分割結(jié)束時,返回NULL。所有delim中包含的字符都會被濾掉,并將被濾掉的地方設(shè)為一處分割的節(jié)點。
2、例程:
#includestdio.h
#includestring.h
int?main(){
char?input[16]="abc,d,ef,g";//待分解字符串
char*?delim=",";//分隔符字符串
char*?p=strtok(input,delim);//第一次調(diào)用strtok
while(p!=NULL){//當返回值不為NULL時,繼續(xù)循環(huán)
printf("%s\n",p);//輸出分解的字符串
p=strtok(NULL,delim);//繼續(xù)調(diào)用strtok,分解剩下的字符串
}
return?0;
}
分享名稱:關(guān)于c語言中分割字串的函數(shù)的信息
文章位置:http://muchs.cn/article10/dospsdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、標簽優(yōu)化、網(wǎng)站排名、品牌網(wǎng)站建設(shè)、建站公司、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)