hw去年上机题1

    技术2022-05-18  9

    删除字符串中所有给定的子串

     

    问题描述:

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

     

    要求实现函数:

    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"字串。

     

     

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    自己写的用库函数了版本。。这段时间再写个不用库函数版本的,再写用那些个算法的吧

     

     

    #include "stdafx.h" #include<stdio.h> #include<string.h> #include<iostream> #include <conio.h> using namespace std; #define SOURCE_LEN 40 #define SUB_LEN 20 int delete_sub_str(const char *str, const char *sub_str, char *result_str) { int num = 0; int i = 0; const char *current = strstr(str,sub_str); char c; if (current == NULL) { printf("no sub_str in str!!!!/n"); } if (current != str)//处理第一个字串之前未匹配的 { for (str; str !=current; str++) { c = *str; result_str[i] = c; i++; } } while(current != NULL)//处理中间 { num+=1; str = current; current = strstr(current+strlen(sub_str),sub_str); str+=strlen(sub_str); for (str; str < current; str++) { c = *str; result_str[i] = c; i++; } } while(*str != '/0')//处理末尾 { c = *str; result_str[i] = c; i++; str++; } printf("/nafter delete the sub:/n%s/n",result_str); return num; } int _tmain(int argc, _TCHAR* argv[]) { printf("please input the source str:/n"); char source[SOURCE_LEN]; char sub[SUB_LEN]; char del[SUB_LEN] = ""; gets(source); printf("please input the sub str:/n"); gets(sub); //printf("%s/n",source); //printf("%s/n",sub); printf("/nnum of subs:/n%d",delete_sub_str(source, sub, del)); getch(); return 0; }

     

     -----------------------------------------------------------------------------------------------------------

    不用库函数的版本:

     

    int delete_sub_str(const char *str, const char *sub_str, char *result_str) { while (*str) { while (*sub_str) { if (*sub_str == *str) break; sub_str++; } if(*sub_str == '/0') { result_str[i] = *str; i++; } str++; sub_str = p; } printf("%s/n",result_str); ... }

     

     

     

     


    最新回复(0)