I am trying to create a function which takes two chars and a char* string. Then run the function and replace each occurence of Char1 with char 2.
E.g. String = Apples. Char 1 = A. Char 2 = B.
Char 1 is present in string so replace all occurrences of Char 1 with char 2.

I've created some code for the function, but I am unable to call it:

/* replace c1 with c2 in s, returning s */
char *substitute(char *s, char c1, char c2)
    char *r = s;
    if (s == 0) return 0;
    for (; *s; ++s)
        if (*s == c1) *s = c2;
    return r;

int main()
    string s = "apples";
    char a;
    char b;

    cout << "Before swap of Char : " << s << endl;

    *substitute(&s, a, b);

    cout << "After swap of Char : " << s << endl;


My question is how do I continue on from here and call the function in main?
Also to note I am a beginner with C++

4 Years
Discussion Span
Last Post by deceptikon

You need to decide whether you want to use C-style strings or C++ std::string. If you want a C-style string, it's called like this:

int main()
    char s[] = "apples";
    char a = 'p';
    char b = 'd';

    cout << "Before swap of Char : " << s << endl;
    substitute(s, a, b);
    cout << "After swap of Char : " << s << endl;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.