2010-10-07 21 views
7
string DelStr = "I! am! bored!"; 
string RepStr = "10/07/10" 

Chcę usunąć wszystkie "!" na DelStr i chcę zamienić wszystkie "/" na "-" w ciągu RepStr.Zamień usuń znak w ciągu znaków

Czy można to zrobić bez wykonywania pętli, aby przejść przez każdą postać?

+0

możliwy duplikat [zamiany znaków C++] (http://stackoverflow.com/questions/1820394/c-character-replace) –

+1

Nie, usunięcie nie było tam adresowane. –

+0

jakkolwiek to zrobisz, potrzebna jest pętla; możesz tego nie robić, na pewno zadzwoni metoda. – vulkanino

Odpowiedz

12

Remove się okrzyki:

#include <algorithm> 
#include <iterator> 

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

Ewentualnie, jeśli chcesz drukować ciąg, nie trzeba się result zmiennej:

#include <iostream> 

std::remove_copy(delStr.begin(), delStr.end(), 
       std::ostream_iterator<char>(std::cout), '!'); 

Replace ukośniki z kreskami:

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

Dzięki! Działa świetnie. – Cornwell

+1

Należy zauważyć, że będzie to oznaczać, że jeśli spróbujesz użyć result.size(), otrzymasz rozmiar destStr, ponieważ wynik będzie również zawierać dodatkowe puste znaki. – deworde

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.) 
Powiązane problemy