C++|分割字符串

实现一个函数,能够得到某个字符串source的第pos个字串,并且字串之间使用sep分割。


int GetnSubStr(const char *source,char *buf,int pos,char sep){
    
    return 0;
}

首先,获取源字符串的长度,避免越界。

// Get source string length.
    int length;
    for(length=0;source[length];length++);

然后定义一些变量:

len  字串长度计数

count 子串数量计数

mode (返回值)字串是否找到

now 当前源字符串的数组下标

    int  len  =0;// Sub string length counter
    int  count=0;// Sub string counter
    bool mode =0;// Getting flag
    int  now  =0;// Offset of source string

接下来寻找第pos个字串

使用一个循环

    while(now<length){
        // ...
    } 

当前位置的字符如果是分割符sep时,需要判断是否为一个字串的结尾(因为源字符串中可能有多个相邻的分割符sep)

        if(source[now]==sep){// When 'sep'
            if(len){// End of sub string.
                len=0;
                count++;
            }
        }

如果不是,那么当前位置是字串的某个位置,需要判断这个字串是否为要分割的字符串

        else{
            if(count==pos){// Got
                buffer[len]=source[now];// Write
                mode=true;
            }
            len++;// 
        }

然后下一个字符

now++;// Next offset

寻找完了,返回分割(寻找)成功与否

return mode;

整个函数的代码如下

int GetnSubStr(
    const char *source,
          char *buffer,
    const int   pos   ,
    const char  sep
){
    // Get source string length.
    int length;
    for(length=0;source[length];length++);
    // Some value
    int  len  =0;// Sub string length counter
    int  count=0;// Sub string counter
    bool mode =0;// Getting flag
    int  now  =0;// Offset of source string
    // 
    while(now<length){
        if(source[now]==sep){// When 'sep'
            if(len){// End of sub string.
                len=0;
                count++;
            }
        }else{
            if(count==pos){// Got
                buffer[len]=source[now];// Write
                mode=true;
            }
            len++;// 
        }
        now++;// Next offset
    }
    return mode;
}

--EOF--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值