Заменить \ удалить символ в строке - PullRequest
8 голосов
/ 07 октября 2010
string DelStr = "I! am! bored!";
string RepStr = "10/07/10"

Я хочу удалить все '!' в DelStr, и я хочу заменить все '/' на '-' в строке RepStr.

Есть ли способ сделать это, не выполняя цикл для прохождения каждого символа?

Ответы [ 2 ]

13 голосов
/ 07 октября 2010

Удалить восклицания:

#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), '!');

Заменить косой чертой:

std::replace(repStr.begin(), repStr.end(), '/', '-');
0 голосов
/ 20 сентября 2013
#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.)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...