当前位置:编程学习 > C/C++ >>

在一个字符串中删除特定字符

#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#include<memory.h>

void Delete_specific_char(char * str1, char * str2)
{
   
   char * phash = (char *)malloc(sizeof(char)*256);
   assert(phash);
   memset(phash, 0, 256);

   int i = 0;
   while(str2[i] != '\0' )
   {
	   phash[str2[i++]] =1;
   }
   
   int newp = 0;
   i = 0;
   while(str1[i] != '\0' )
   {
	   if(phash[str1[i]] ==1)
	   {
		   i++;
	   }
	   str1[newp++] = str1[i];
	   i++;
   }
  str1[newp  ] ='\0';
   


  free(phash);
}

int main()
{   
 char a1[] = "they are student.";  
 char a2[] = "aeiou";
 Delete_specific_char(a1, a2);
 printf("%s",a1);
 printf("%s\n",a2);
 return 0 ;	
}
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include <memory.h>

void Delete_specific_char(char * str1, char * str2)
{   
	assert(str1);
	assert(str2);
    char * phash = ( char * )malloc( sizeof(char)*256 );//先将str2在phash中映射一遍
	memset(phash,0,256);
	int i = 0;
	while ( str2[i] != '\0')
	{   
		phash[str2[i]] = 1;
		i++;
	}
	char * fast = str1;  //这个指针用来扫描str1
	char * slow = str1;  //这个指针用来修改str1,存放的是下一个待修改的位置
	int j = 0;
	while (fast[j]!= '\0')  //开始扫描str1
	{   
		if (phash[*fast] != 1)  //如果fast所指向的字母在str2中没有,fast,slow就都指向下一个
		{
             
			 *slow =*fast;
			 fast++;
			 slow++;
		}
		else     //如果fast所指向的字母在str2中存在,那么fast指向下一个
		{     
			 
		      fast++;
			  while (phash[*fast])//继续扫描,把连续的在str2中的字符都跳过,直到找到一个非str2中的字符
			  {
				  fast++;
			  }
			  *slow = *fast;  //将那个非str2的字符赋给slow当前所指向的字符  
			  slow++;   //继续扫描,
			  fast++;
		}
	}
	*slow = '\0';
	free(phash);
}

int main( )
{
   char a1[] = "they are  student. ";
   char a2[] = "aeiouac";

   Delete_specific_char(a1, a2);
   int i = 0;

   while (a1[i] !='\0')
   {
	   printf("%c",a1[i]);
	   i++;
   }
   printf(":\n");
   
   return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,