【编程题目】在字符串中删除特定的字符

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

我的思路:先扫描第一个字符串,判断是否是第二的字符串的字符,是则跳过,记录跳过多少个,后面的不被删除的就前移。

/*
63.在字符串中删除特定的字符(字符串)。
题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
例如,输入”They are students.”和”aeiou”,
则删除之后的第一个字符串变成”Thy r stdnts.”。
*/
#include <stdio.h>
#include <string.h>

void moveout(char * c1, char * c2)
{
    bool flag = false; //是否保留下来
    int d = 0; //记录保留下来的字符需要移动几位
    int i, j;
    for(j = 0; c1[j] != ''; j++)
    {
        flag = false;
        for(i = 0; c2[i] != ''; i++)
        {
            if (c1[j] == c2[i]) 
            {
                flag = true;
                d++;
                break;
            }
        }
        if (flag == false)
        {
            c1[j - d] = c1[j];
        }        
    }
    c1[j - d] = '';
}

int main()
{
    char a[50] = "i want to go home";
    char b[6] ="aeiou";
    moveout(a, b);

    return 0;
}

网上看到一个不错的方法,比我的简洁多了,也快。 用到了 字符串hash

http://www.cnblogs.com/gina/p/3247177.html 讲的很清楚

#include <iostream>
#include <cstring>

char * string_del_characters( char * const src, const char * const dest )
{
   int destLen = strlen( dest );
   int hash_table[256] = { 0 };
   char * p = src;
   int index = 0;
   for( int i = 0; i < destLen; i++ )
   {
      hash_table[ (int)dest[i] ] = 1;
   }
   while( *p != '' )
   {
      if( 0 == hash_table[(int)*p] )
      {
         src[index++] = *p;
      }
      p++;
   }
   src[index] = '';
   return src;
}

int main( int argc, char ** argv )
{
   char src[] = "They are students.";
   char dest[] = "aeiou";
   char * pResult = string_del_characters( src, dest );
   std::cout << pResult << std::endl;
}
原文地址:https://www.cnblogs.com/dplearning/p/3914580.html