删除特定字符

本文介绍了一种使用C语言从字符串中移除特定字符的方法。通过两种不同的实现方式,一种利用字符作为数组下标,另一种借助STL容器,展示了如何高效地完成任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思 路 : 使用字符作为数组的下标(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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值