zoukankan      html  css  js  c++  java
  • 天天算法02——删除字符串中所给定的字符串

    题目:(华为2010上机题)

    在给定字符串中查找所有特定子串并删除,如果没有找到相应子串,则不作任何操作。
    要求实现函数:
    int delete_sub_str(const char *str, const char *sub_str, char *result_str)
    【输入】 str:输入的被操作字符串
             sub_str:需要查找并删除的特定子字符串
    【输出】 result_str:在str字符串中删除所有sub_str子字符串后的结果
    【返回】 删除的子字符串的个数

    解答:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <malloc.h>
    
    int delete_sub_str(const char *str, const char *sub_str, char *result_str)
    {
    	int count = 0;
    	int tmp = 0;
    	int sub_tmp = 0;
    	int start_ptr = 0;
    	int result_ptr = 1;
    
    	while(*(str+tmp) != '\0'){
    		if(*(str+tmp) == *(sub_str+sub_tmp)){
    			tmp++;
    			sub_tmp++;
    			while(*(sub_str+sub_tmp) != '\0'){
    				if(*(str+tmp) != *(sub_str+sub_tmp))
    					break;
    				else{
    					tmp++;
    					sub_tmp++;
    				}
    			}
    			if(*(sub_str+sub_tmp) != '\0'){
    				sub_tmp = 0;
    				continue;
    			}
    			else{
    					count++;
    					if(tmp-sub_tmp-start_ptr != 0){
    						realloc(result_str,strlen(result_str)+tmp-sub_tmp-start_ptr+1);
    						memset(result_str+result_ptr-1, '\0', tmp-sub_tmp-start_ptr);						
    						strncat(result_str, str+start_ptr, tmp-sub_tmp-start_ptr);
    					}
    					result_ptr += tmp-sub_tmp-start_ptr;
    					start_ptr += tmp-start_ptr;
    					sub_tmp = 0;				
    			}
    		}
    		else
    			tmp++;	
    	}
    	realloc(result_str,strlen(result_str)+tmp-sub_tmp-start_ptr+1);
    	memset(result_str+result_ptr-1, '\0', tmp-sub_tmp-start_ptr);
    	strncat(result_str, str+start_ptr, tmp-sub_tmp-start_ptr);
    
    	return count;
    }
    
    int main()
    {
    	char *tmp = NULL;
    	int n;
    	tmp = malloc(1);
    	memset(tmp,'\0',1);
    	n = delete_sub_str("ababacdeabafg", "aba", tmp);
    	printf("find %d substring.\n",n);
    	printf("the result is:%s\n",tmp);
    	free(tmp);
    	return 0;
    }

    参考资料:

    http://bbs.auxten.com/read.php?tid=674773

  • 相关阅读:
    Go语言开发Windows应用
    go 调用windows dll 的方法
    thinkPHP5 命名空间别名
    thinkPHP5 类库包注册
    thinkphp5 默认配置代码
    edusoho twig 引入文件功能
    edusoho 查找网址对应的控制器和模板页面
    启动Nginx 出现 nginx: [emerg] unknown directive "锘?user" 错误
    eduSOHO 首页模板 全部课程模块代码
    twig 模板控制器对应列表
  • 原文地址:https://www.cnblogs.com/bo083/p/2226377.html
Copyright © 2011-2022 走看看