删除字符串中某些特定的字符

来源:互联网 发布:重庆大学博雅学院 知乎 编辑:程序博客网 时间:2024/05/21 07:46


1. 描述

输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”。


2. 思路

字符的个数是有限的(不考虑Unicode字符),一个char型字符为一个字节占八位,共有 2^8 = 256个字符,除去ASCII为零的字符'\0'外共有255个字符,因此可以建立一个字符到相应ASCII的哈希数组。数组初始化为全零。数组的下标为字符的ASCII,要删除的字符对应的ASCII处的的哈希值设为1。

从头扫描字符串,遇见要删除的字符时把字符设成'\0',同时设置一计数器统计删除的字符的次数。


3. 代码


void delChar(char str[], char delchar[]){int ascii[256] = {0};   char2ASCII(ascii, delchar);//时间复杂度为O(strlen(delchar))char *p;int count;for (count = 0, p = str; *p; p++)//时间复杂度为O(strlen(str)){if (ascii[*p]){*p = '\0';count++;}}for (p = str, count += 1; count--; p = p + strlen(p) + 1) //时间复杂度为O(strlen(del)){printf("%s", p);}printf("\n");}

其中建立字符串到相应ASCII的哈希数组的函数如下:

void char2ASCII(int ascii[], char str[]){//ascii[] indices range from 1 to 255memset(ascii, 0, 256);char *p;for (p = str; *p; p++) {ascii[*p] = 1;}}

总的时间复杂度为O(strlen(str) + strlen(del)).

测试如下:

#include <stdio.h>#include <stdlib.h>#include <string.h>void delChar(char str[], char delchar[]);void char2ASCII(int ascii[], char str[]);int main(void){char str[] = "They are students.";char delchar[] = "aeiou";printf("Delete \"%s\" characters from string \"%s\":\n", delchar, str);delChar(str, delchar);return 0;}

输出:



原创粉丝点击