按照特定字符分割string字符串


#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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM