#include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { /* //法1,使用find函數 string st="1001,88.67,1003,22.1,1002,76.3"; int pos_st=0; pos_st=st.find(","); if(pos_st<0)//判空 { cout<<"letter not exist"<<endl; return 0; } if(st[st.size()-1]!=',')//如果字符串最后不是逗號,添加逗號 { st.append(","); } pos_st=0; while(pos_st<st.size()) {//使用string 的find函數 int pos_st_next=st.find(",",pos_st); string sst=st.substr(pos_st,pos_st_next-pos_st); pos_st=pos_st_next+1; cout<<sst<<endl; } */ //法2,類似快慢指針 int slow(0),fast(0); string st2="1001,88.67,1003,22.1,1002,76.3"; while(fast<st2.size()) { if(st2[fast]==',')//相等保留逗號位置 { string res=st2.substr(slow,fast-slow);//取到逗號為止的內容 cout<<res<<endl; fast=fast+1;//跳過當前逗號 slow=fast;//從逗號的后一個開始找下一個逗號 } ++fast; } if(st2[st2.size()-1]!=',')//字符串最后是否為逗號 { cout<<st2.substr(slow,st2.size()-slow); } return 0; }
