String

Hi! I have a basic question. How do you remove a character from string. Let's say the user input "This is a string" then asked what char to remove and lets say the character 'i'. Do I need to use a for loop? or mix it with the function in the string library.I just get confused sometimes. Any suggestions will be appreciated.
strings are containers, so you can use the usual erase-remove idiom for containers

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <algorithm>
#include <string>
int main() {
    std::string s = "This is a string";
    char c = 'i';
    
    s.erase(std::remove(s.begin(), s.end(), c), s.end());
    
    std::cout << s << '\n';
}


and yes, you can also do a for-loop that calls functions from the string library, such as

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
int main() {
    std::string s = "This is a string";
    char c = 'i';
    
    for(auto pos = s.find(c); pos != s.npos; pos = s.find(c, pos))
        s.erase(pos, 1);
       
    std::cout << s << '\n';
}


As with any basic question, there are many ways to do it. For another example, you could just call std::regex_replace with an empty replacement string.
Last edited on
Another option:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

using namespace std;

string RemoveChar(const string& input, const char c)
{
  string result;
  result.reserve(input.size());
  for(const char ch: input)
  {
    if (ch != c)
    {
      result += ch;
    }
  }
  return result;
}

int main() 
{
    string s = "This is a string";
    char c = 'i';
    
    string res = RemoveChar(s, c);
       
    cout << res << '\n';

    system("pause");
}
Topic archived. No new replies allowed.