当前位置:首页 > 通信资讯 > 正文

在一个字符串中找到第一个只出现一次的字符
题目:

在一个字符串中找到第一个只出现一次的字符。如输入 abaccdeff,则输出 b。

分析:

一个字符串存储的都是ASCII字符,其ASCII范围不超过255。

因此可以再创建一个255个元素的数组存储字符串中字符出现的个数。

通过两次遍历即可求得。

代码实现(GCC编译通过):

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include "stdio.h" #include "stdlib.h" //查找字符串中第一个只出现一次的字符 char firstSingle(char * str); int main(void) { char str[] = "abaccdeff"; char tmp = firstSingle(str); printf("%c\n",tmp); return 0; } char firstSingle(char * str) { //ASCII表有255个字符,创建一个255个元素的映射数组初始为0 int asc[255] = {0}; int i; //遍历字符串,同时做字符的ASCII值映射到数组下标统计出现次数; for(i=0;str[i]!='\0';i++) asc[str[i]]++; //再次遍历,找到第一个出现一次的字符即为所求 for(i=0;str[i]!='\0';i++) if(asc[str[i]] == 1) return str[i]; //否则返回空 return '\0'; }

注:

  • 这种值映射到下标是比较常见的一种方式,一些情况下避免了数组的遍历。
  • 数组初始化可以使用函数:void *memset(void *s, int ch, sizet n);
  • 还可以使用指针实现。


在字符串中找出连续最长的数字串
题目:

写一个函数,它的原形是 int continumax(char *outputstr,char *intputstr)

功能:

在字符串中找出连续最长的数字串,并把这个串的长度返回,

并把这个最长数字串付给其中一个函数参数 outputstr 所指内存。

例如:"abcd12345ed125ss123456789" 的首地址传给 intputstr 后,函数将返回 9,

outputstr 所指的值为 123456789

题目也比较简单,有一点需要注意

代码实现(GCC编译通过):

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 #include "stdio.h" #include "stdlib.h" int continumax(char * outputstr,char * inputstr); int main(void) { char *in = "abcd12345ed125dd123456789"; char *out = (char *)malloc(sizeof(char)*100); int i = continumax(out,in); printf("%d\n",i); printf("%s\n",out); return 0; } int continumax(char * outputstr, char * inputstr) { int len,max,i; char *p; len = max = 0; //若写成while(inputstr != '\0'),当字符串结尾出现最长数字串则无法处理 while(1) { if(*inputstr >= '0' && *inputstr <= '9') { len++; } else { if(len >max) { max = len; p = inputstr - len; } len = 0; } if(*inputstr++ == 0) break; } for(i = 0;i<max;i++) *outputstr++ = *p ++; *outputstr = '\0'; return max; }
如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。