Hi,

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;

    system("pause");
}

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++

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.