替换\删除字符串中的字符

时间:2010-10-07 13:51:21

标签: c++ string

string DelStr = "I! am! bored!";
string RepStr = "10/07/10"

我要删除所有'!'在DelStr上我想在RepStr字符串上用' - '替换所有'/'。

有没有办法在不循环播放每个角色的情况下执行此操作?

2 个答案:

答案 0 :(得分:13)

Remove惊叹:

#include <algorithm>
#include <iterator>

std::string result;
std::remove_copy(delStr.begin(), delStr.end(), std::back_inserter(result), '!');

或者,如果要打印字符串,则不需要result变量:

#include <iostream>

std::remove_copy(delStr.begin(), delStr.end(),
                 std::ostream_iterator<char>(std::cout), '!');
带有破折号的

Replace斜杠:

std::replace(repStr.begin(), repStr.end(), '/', '-');

答案 1 :(得分:0)

#include<iostream.h>
#include<string.h>
#include<conio.h>
void main()
{
clrscr();
char a[200],ch,ch1;
int temp=0,i,j,x,len,z,f,k=0;
cout<<"Enter String: ";
cin.getline(a,150);
len=strlen(a);
cout<<"\n\nLength Of String: ";
cout<<len;
cout<<"\n\n\nReplace: ";
cin>>ch;
cout<<"\n\nReplace with: ";
cin>>ch1;
for(i=0;i<len;i++)
{
if(ch==a[i])
{
temp=a[i];
a[i]=ch1;
}
}
cout<<"\n\nUpdated String: ";
for(i=0;i<len;i++)
{
cout<<a[i];
}
getch();
}

Example: 
Enter String: Hey! How Are You.
Replace: H
Replace with: m
Output: mey! mow Are You.

(Note: Every character has its ascii code. Such as 'H' and 'h' are two different characters.)