Benjamin
Benjamin

Reputation: 345

How would I get a function to replace all instances of a char in an array?

I have a small application being written in ANSI C using GCC in Ubuntu. Inside one of my files, I have the following function:

void Decipher(char *pCipherText, char *pLetter, char *pReplacement) {
    for (; *pCipherText != '\0'; pCipherText++) {
        if (*pCipherText == *pLetter) {
            SortChar(pCipherText, pReplacement);
        }
    }
}

The function for SortChar():

void SortChar(char *pChA, char *pChB) {
    char tempCh; /*temp variable*/
    tempCh = *pChA; /*store old value before it is overwritten*/
    *pChA = *pChB; /*overwrite old value*/
    *pChB = tempCh; /*complete the swap*/
}

pCipherText is a pointer to an array of chars, pLetter is a pointer to a char, and pReplacement is a pointer to a char. I would like the function to iterate through the entire array, using the pointer pCipherText, and replace each occurrence of pLetter's value in the array with pReplacement's value. Right now, the function only replaces the first instance of pLetter in pCipherText.

How would I modify the function to replace all of the occurances of pLetter with pReplacement? Thanks.

Upvotes: 1

Views: 62

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

You should replace

SortChar(pCipherText, pReplacement);

with

*pCipherText = *pReplacement;

Your SortChar() will swap its arguments, and I believe it is misnamed.

Upvotes: 2

Related Questions