/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
How would I index the str so that I would replace every 's' with 'r'.
Thanks.
You don't need to index the string. You have a pointer to the character you want to change, so assign via the pointer:
*pch = 'r';
In general, though, you index using []
:
ptrdiff_t idx = pch - str;
assert(str[idx] == 's');
You can use the following function:
char *chngChar (char *str, char oldChar, char newChar) {
char *strPtr = str;
while ((strPtr = strchr (strPtr, oldChar)) != NULL)
*strPtr++ = newChar;
return str;
}
It simply runs through the string looking for the specific character and replaces it with the new character. Each time through (as with yours), it starts with the address one beyond the previous character so as to not recheck characters that have already been checked.
It also returns the address of the string, a trick often used so that you can use the return value as well, such as with:
printf ("%s\n", chngChar (myName, 'p', 'P'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With