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


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 255
	memset(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;
}

输出:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值