通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。比如字符串"abacacde",过滤结果为"abcde"。
要求实现函数:
【输入】pInputStr:输入字符串void stringFilter(const char *pInputStr, long lInputLen, char *pOutputStr);lInputLen:输入字符串长度
【输出】pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长。
方法(1):
方法(2):#include <stdio.h> #include <string> #include <malloc.h> void stringFilter(const char* pInputStr, long lInputLen, char* pOutputStr) { int i,j; int k = 1; pOutputStr[0] = pInputStr[0]; bool bFlag = true; for (i = 1; i < lInputLen; i++) { for (j = i - 1; j >= 0; j--) { if (pInputStr[j] == pInputStr[i]) { bFlag = false; break; } } if (bFlag == false) { bFlag = true; continue; } else { pOutputStr[k++] = pInputStr[i]; } } pOutputStr[k] = '\0'; } void main() { char* str; str = (char*)malloc(sizeof(char)); printf("请输入字符串\n"); scanf("%s",str); //字符串的长度 long lStrLen = strlen(str); //输出字符串 char* result; result = (char*)malloc(sizeof(char) * lStrLen); stringFilter(str,lStrLen,result); printf("过滤后的字符串:%s\n",result); }
#include <stdio.h> #include<string.h> #include<malloc.h> void stringFilter(const char *p_str, long len, char *p_outstr) { int array[256]={0}; const char *tmp = p_str; for(int j=0;j<len;j++) { if(array[tmp[j]]==0) *p_outstr++= tmp[j]; array[tmp[j]]++; } *p_outstr = '\0'; } void main() { char *str = "cccddecc"; int len = strlen(str); char * outstr = (char *)malloc(len*sizeof(char)); stringFilter(str,len,outstr); printf("%s\n",outstr); free(outstr); outstr = NULL; }
1041

被折叠的 条评论
为什么被折叠?



