String Manipulation at every odd or even

Hey guys I am pretty new to c++ programming and would like some advice . Basically I am busy with string manipulation , I need to write a code that will delete every odd occurrence (1,3,5 ext) "t" in a string . Can you please help me with reference my current code is. Also how do I add a character at every even(2,4,6) "t" not deleted?

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
 #include <iostream>
#include <string>

using namespace std;

int main ()
{
    string sentence;

    int position ;

    cout << " Enter the sentence " << endl;
    getline(cin, sentence , '\n');

    for(int i=0; i<sentence.length(); i++)
    {
        if(sentence[i] == 't') sentence.erase(i,1);
    }

    cout << sentence ;


    return 0;
}
Last edited on
delete every odd occurrence (1,3,5 ext)
Find first 't', delete it, continue search from that place until you find another 't', do not delete it, etc.

You can do this by either looping, or by calling a string member function find (4th overload): http://en.cppreference.com/w/cpp/string/basic_string/find

To alternate between deleting and retaining, use boolean variable. Set it to true in the beginning and flip it each time you encounter a 't'.
Topic archived. No new replies allowed.