首页 > 编程知识 正文

c语言字符串分割split,c语言读取逗号分割的字符串

时间:2023-05-06 04:43:06 阅读:37033 作者:595

文章目录1 .自实现split (2. string stream3. istringstream4. getline ) )实现split )。

1 .自己split(voidsplit ) constchar*s,vectorstring strs,char delim=' ' ) if ) s==nullptr ) ) { return; }常数char * head,*tail; head=tail=s; while(*head!=' ' ) {while(*head!='' *head==delim ) { head; } tail=head; while(*tail!='' *tail!=delim({tail; (if )头!=tail (strs.push _ back (字符串(head,tail ) ); head=tail; } else { break; } }

将字符串s按delim表示的字符分割,放入向量中。

在搜索过程中,在堆栈概述中找到了另外两种容易理解的方法。

2.string stream int main ((stringstr=' I love world!' ; string str_temp; stringstream ss; strss; while (! ss.eof () ) { ssstr_temp; coutstr_tempendl; }这种方法的局限性是不能用非空格字符拆分字符串

3.istringstreamistringstreamstr (高可靠度); 字符串输出; wile(strout ) {cout out endl; }开车

this is a sentence 4. getline ()为split ) ) voidsplit ) ConstSTD3360:strings,STD : vectors TD 3360: string elems std:string item; while(STD:3360getline(ss,item,delim ) ) elems.push _ back (item ) ); }}int main () { string line='asd fasdf fadf fa '; 向量字符串; 分裂(line,strs ); for(autos:strs ) { cout s endl; }返回0; }正如名称所示,} getline函数用于检索单行数据,但也可以将第三个参数更改为其他字符,并将其他字符用作行分隔符。

但是,这种实现的缺点是,由于getline每次遇到一个行分隔符时都会返回,所以在分隔符连续的情况下是无法处理的。

例如:

stringstr=' dsadsadsdsadasdwwwweeee '; 打印结果如下。

dsadsad sdsadasd wwwww eeeee

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。