- 論壇徽章:
- 0
|
思路就是空間換時間。用一個26字節(jié)的數(shù)組c來記錄哪些字母需要替換,然后掃描整個字符串,用其ascii碼-'a'或'A'來做下標(biāo)去查看是否需要替換。
- #include <stdio.h>
- #include <string.h>
- #include <malloc.h>
- char c[26] = {0};
- void setflg(char* str, int len)
- {
- for(int i = 0; i < len; i++)
- {
- char idx = (str[i] >= 'A' && str[i] <= 'Z')?(str[i] - 'A'):(str[i] - 'a');
- c[idx] = 1;
- }
- }
- void compareStr(char* str, int len)
- {
- for(int i=0;i < len; i ++)
- {
- char idx = (str[i] >= 'A' && str[i] <= 'Z')?(str[i] - 'A'):(str[i] - 'a');
- if (c[idx] == 1)
- {
- str[i] = '\0';
- }
- }
- }
- void trimStr(char* inStr, char* outStr, int len)
- {
- int idx = 0;
- for(int i = 0; i < len; i++)
- {
- if(inStr[i] != '\0')
- {
- outStr[idx] = inStr[i];
- idx++;
- }
- }
- }
- main()
- {
- char a1[] = "Student is study";
- char a2[] = "senu";
- int len1 = strlen(a1);
- int len2 = strlen(a2);
- setflg(a2, len2);
- compareStr(a1, len1);
- char* outStr = (char*)malloc(sizeof(a1));
- memset(outStr, 0, sizeof(a1));
- trimStr(a1, outStr, len1);
- printf("%s\n", outStr);
- free(outStr);
- }
復(fù)制代碼
[ 本帖最后由 gz80 于 2009-9-16 17:47 編輯 ] |
|