How to delete characters in a string?
10,492
Solution 1
First, you did not define any c or s variables. Second, your parameter in remove function is const, that means s is unchangeable. The code below works in my VS2013.
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <limits>
using namespace std;
string remove(char* charToRemove, string &str){
//string s = "Pineapple";
//char chars[] = "p";
for (unsigned int i = 0; i < strlen(charToRemove); ++i)
{
str.erase(remove(str.begin(), str.end(), charToRemove[i]), str.end());
}
cout << str << endl;
return str;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str("Pineapple");
char chars[] = "p";
remove(chars, str);
int i;
cin >>i;
}
Solution 2
Simply get the position of first 'p'
from "Pineapple"
using string::find()
, then use string::erase()
. No need to put string::erase()
inside the loop.
string remove(char to_rem, string s) {
size_t pos = s.find( to_rem );
s.erase(pos, count(s.begin(), s.end(), to_rem) );
return s;
}
Modified code:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string remove(char to_rem, string s) {
size_t pos = s.find( to_rem );
s.erase(pos, count(s.begin(), s.end(), to_rem) );
return s;
}
int main() {
cout << remove('p', "Pineapple");
}
Output:
Pineale
Author by
Beezy
Updated on July 14, 2022Comments
-
Beezy almost 2 years
I am trying to write a program hat removes the character 'p' in Pineapple to output the word Pineale. Here is my current code. I found similar problems to this and thought this code would work but it is not unfortunately. Any help is appreciated!
#include <iostream> #include <algorithm> #include <string> #include <cstdlib> #include <limits> using namespace std; int main(){ remove(c,s); } string remove(char c, const string & s){ string s = "Pineapple"; char chars[] = "p"; for (unsigned int i = 0; i < strlen(chars); ++i) { s.erase(remove(s.begin(), s.end(), chars[i]), s.end()); } cout << s << endl; return s; }