文章标题
来源:互联网 发布:淘宝买dota2饰品封号 编辑:程序博客网 时间:2024/06/05 08:01
今天在做C语言经典实例100题中遇到的一题,其中的方法很值得学习,第一种是我自己所编写的程序,方法很一般,是个人都能想到。而第二种方法则非常巧妙。
32题目:删除一个字符串中的指定字母,如:字符串 “aca”,删除其中的 a 字母。
#include <stdio.h>#include <string.h>int main(){ char str[100]; char c; printf("请输入一个字符串:"); scanf("%s",str); printf("请输入需要删除的字母:"); getchar(); scanf("%c",&c); int i,count=0; for (i=0; i<strlen(str); i++) { if (str[i] != c) { str[count++] = str[i]; } } str[count] = '\0'; printf("%s\n",str);}
这种方法是通过建立一个ascii表大小的数组,数组中的数值全为0,把需要去除的字母对应位置上的数组赋值1,通过字符串中的字符与表进行比较来确定是否去除。
#include<stdio.h>#include<stdlib.h>#include<string.h>// 删除字符串中指定字母函数char* deleteCharacters(char * str, char * charSet){ int hash [256]; if(NULL == charSet) return str; for(int i = 0; i < 256; i++) hash[i] = 0; for(int i = 0; i < strlen(charSet); i++) hash[charSet[i]] = 1; int currentIndex = 0; for(int i = 0; i < strlen(str); i++) { if(!hash[str[i]]) str[currentIndex++] = str[i]; } str[currentIndex] = '\0'; return str;}int main(){ char s[2] = "a"; // 要删除的字母 char s2[5] = "aca"; // 目标字符串 printf("%s\n", deleteCharacters(s2, s)); return 0;}
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- Lua模拟继承行为
- C++ 引用
- 缓存报错-初始化失败 ERROR [org.springframework.web.context.ContextLoader] - context initialization failed
- 有趣的数列[HNOI2009][Codevs2337]
- JavaScript学习笔记(1)
- 文章标题
- ElasticsSearch——HighLights
- CSS绘图:墙
- Jquery图片上传大小限制
- INVALID BINARY : Your binary is not optimized for iPhone 5 As of May 1
- javaScript文档中常用的集合
- LLDB调试命令(一) p 和 po 命名行的鼻祖 expression 命令
- scala集合
- iOS 基础篇4—懒加载