删除特定字符

来源:互联网 发布:财务报表主要数据分析 编辑:程序博客网 时间:2024/06/07 23:40

思 路 : 使用字符作为数组的下标(C语言允许把字符映射为整数去充当数组的下标)或者作为hash表的关键字。

viod removechars (char str[], char remove[])
注意,remove中的所有字符都必须从str中删除干净。

例如,如果str: "Battle of the Vowels: Hawaii vs. Grozny",

             remove: "aeiou",

            结 果 : str转换成"Bttl f th Vwls: Hw vs. Grzny"。

 

#include <iostream>
#include <string.h>
using namespace std;
void removechars(char str[] , char remove[]);  
void main()
{
 char str[50],remove[10];
 cout<<"请输入主字符串: ";
 cin.getline(str,50);
 cout<<"请输入要删除的字符集合: ";
 cin>>remove;
 cout<<"输出删除特定字符集后的str: ";
 removechars(str,remove);
 cout<<str<<endl;
}

void removechars(char str[], char remove[])
{  
 int src,dst,removearray[256];
 for(src=0;src<256;src++)
 {
  removearray[src] = 0;
 }
 src=0;
 while(remove[src])
 {
  removearray[remove[src]]=1;
  src++;
 }
 
 src=dst=0;
 do
 {
  if(!removearray[str[src]])
   str[dst++]=str[src];
 }while(str[src++]);
}

 

 

 

 

(二)

 

#include <iostream>
#include <vector>
using namespace std;

bool find(char c,std::vector<char> &subStr)
{
 std::vector<char>::iterator iter;
 for(iter=subStr.begin();iter!=subStr.end();++iter)
  if(*iter == c)
   return true;
 return false;
}

void strDeal(char *str,char *substr)
{
 char strTemp[1000];
 std::vector<char> subStr;
 int j = 0;
 while(substr[j])
 {
  subStr.push_back(substr[j]);
  j++;
 }
 j = 0;
 int i = 0;
 while(str[j])
 {
  if(!find(str[j],subStr))
   strTemp[i++] = str[j];
  j++;
 }
 strTemp[i] = '/0';
 cout<<strTemp<<endl;
}

int main()
{
 char str[1000];
 cin.getline(str,1000);
 strDeal(str,"aeiou");
 return 0;
}

原创粉丝点击