void reverseWords(string &s) { string s_result=""; char *s_dup=strdup(s.c_str()); // first split, outside loop char *splitpoint=strtok(s_dup," "); while(splitpoint!=NULL) { //reverse each split word in place, int splitlength=strlen(splitpoint); for(int i=0;i<splitlength/2;i++) { char tmp=splitpoint[i]; splitpoint[i]=splitpoint[splitlength-i-1]; splitpoint[splitlength-i-1]=tmp; } //change char* to string, then each time concatenate to new string string reversesplitword=splitpoint; splitpoint=strtok(NULL," "); if(splitpoint!=NULL) s_result+=reversesplitword+" "; else s_result+=reversesplitword; } //reverse s_result; string tmp=""; for(int i=0;i<s_result.length();i++) tmp=s_result[i]+tmp; s=tmp; }
char *splitpoint=strtok(s_dup," "); while(splitpoint!=NULL) { splitpoint=strtok(NULL," "); }
#include<stringstream> ... str=" zhang rui chang "; istringstream istr(str); while(str>>splitstr) { //process for each splitted str, splitstr; }
如果修改delim的话,用getline函数改下就好了
www.haogongju.net/art/1554996
std::string token, text("Here,is,some:text"); //声明两个string token为空, text初始化为 "Here, is, some:text" std::stringstream iss(text); //声明一个stringstream类型 对象iss, 并将其赋值给 text while ( getline(iss, token, ',') ) //从iss 读取字符串,并写入给字符串 token, 截断符使用 ',' 代替默认的截断符 '\n', 直到读到iss的结尾位置为止 { std::cout << token << std::endl; //输出每次截断的新内容 ...即 token的值 11 }
String的实现,也可以考虑迭代器实现
blog.csdn.net/butterfly_dreaming/article/details/10142443
//注意:当字符串为空时,也会返回一个空字符串
void split(std::string& s, std::string& delim,std::vector< std::string >* ret) { size_t last = 0; size_t index=s.find_first_of(delim,last); while (index!=std::string::npos) { ret->push_back(s.substr(last,index-last)); last=index+1; index=s.find_first_of(delim,last); } if (index-last>0) { ret->push_back(s.substr(last,index-last)); } }char* 也可以实现,但是和上面没本质区别
另外还有一个细节就是char string[ ]=”C++ programming language”;
用strlen 是24, 但是sizeof 25, 原因是strlen是基于字符串本身的长度,当然不算结束符了,而sizeof是占得内存字节数,\0是占内存,切腹属于该字符串
char *a="C++ programming language"; cout<<strlen(a)<<endl<<sizeof(a)<<endl;
结果是:24和4,所以大家可以体会给char a[] 和char*a赋一个字符串的巨大区别了吧
但是如果 cout<<a<<endl<<(void*)a<<endl 前面输出的居然是字符串值,而不是一个地址值,而后面要转换成泛型指针才能输出地址值,小伙伴们都惊呆了,想起了C++书当时提到的C++智能处理。
再次感谢博主帮我回忆了C++字符串处理
www.weixueyuan.net/view/5851.html
由编程珠玑字符串倒置问题拓展到split之C\C++实现,布布扣,bubuko.com
原文地址:http://blog.csdn.net/richardzrc/article/details/30320499