现在的位置: 首页 > 综合 > 正文

删除字符串中所子串【编程】

2014年07月07日 ⁄ 综合 ⁄ 共 1212字 ⁄ 字号 评论关闭

1. 删除字符串中所有给定的子串(40分)

问题描述: 
在给定字符串中查找所有特定子串并删除,如果没有找到相应子串,则不作任何操作。

要求实现函数: 
int delete_sub_str(const char *str, const char *sub_str, char *result_str)

【输入】 str:输入的被操作字符串

         sub_str:需要查找并删除的特定子字符串

【输出】 result_str:在str字符串中删除所有sub_str子字符串后的结果

【返回】 删除的子字符串的个数

注:

I、   子串匹配只考虑最左匹配情况,即只需要从左到右进行字串匹配的情况。比如:

在字符串"abababab"中,采用最左匹配子串"aba",可以匹配2个"aba"字串。如果

匹配出从左到右位置2开始的"aba",则不是最左匹配,且只能匹配出1个"aba"字串。

II、  输入字符串不会超过100 Bytes,请不用考虑超长字符串的情况。

示例 
输入:str = "abcde123abcd123"

sub_str = "123"

输出:result_str = "abcdeabcd"

返回:2

 

输入:str = "abcde123abcd123"

sub_str = "1234"

输出:result_str = "abcde123abcd123"

返回:0

#include <iostream>
#include <vector>

using namespace std;

int my_words(char input[], char delstr[], char output[])
{
    vector<int> index_num;
    char temp[20] = {'\0'};
    char *pinput = input;
    for(int i=0; i<strlen(input)-strlen(delstr); i++)
    {
        if(strstr(pinput, delstr)!=NULL)
        {
            strncpy(temp, pinput, strstr(pinput, delstr)-pinput);
            strcat(output, temp);
            index_num.push_back(strstr(pinput, delstr) - input);// = 1;
            pinput = strstr(pinput, delstr)+strlen(delstr);
        }
    }
    if(index_num.size()>0)
        strcat(output, pinput);
        else
    strcpy(output, input);
    return index_num.size();
}
int main()
{
    char inputs[100], outputs[100], temp[20];
    memset(outputs, '\0', 100);
    gets(inputs);
    gets(temp);
    cout<<my_words(inputs, temp, outputs)<<endl;
    puts(outputs);
    return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.