Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I replace the character in this example using strchr?

Tags:

c

string

/* 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.

like image 967
T.T.T. Avatar asked Sep 22 '10 18:09

T.T.T.


2 Answers

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');
like image 61
Steve Jessop Avatar answered Nov 15 '22 09:11

Steve Jessop


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'));
like image 42
paxdiablo Avatar answered Nov 15 '22 09:11

paxdiablo