在字符串中删除特定的字符

    技术2022-05-20  54

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

    分析此题的文章很多(能够讲解清楚是种能力),给出参考性代码,用代码说话

     

    #include < stdio.h > #include < memory.h > /* **********************************************************************************36输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”。********************************************************************************** */ int delchar( char * src, char * dst); int main(){ char src[] = " They are students. " ; char del[] = " aeiou " ; delchar(src, del); printf( " Output : %s/n " ,src); return 0 ;} int delchar( char * src, char * dst){ char * begin = src; char * end = src; char hashtable[ 256 ]; int i = 0 ; memset(hashtable, 0 , sizeof (hashtable)); while ( * dst) ++ hashtable[ * dst ++ ]; while ( * end) { if ( ! hashtable[ * end]) // del character not detected { * begin = * end ; ++ begin; } ++ end; } * begin = ' /0 ' ;}

     

    此段代码有两点注意

    1.用到了hash的思想来映射字符串。

    2.两个临时指针恰到好处,边遍历边覆盖(即删除操作)

    参考文章

    每天一道算法题12 在字符串中删除特定的字符 

    从字符串中删除指定字符 


    最新回复(0)