开发者

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

/* 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 a开发者_如何转开发t %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'));


void reeplachar(char *buff, char old, char neo){
    char *ptr;        
    for(;;){
        ptr = strchr(buff, old);
        if(ptr==NULL) break; 
        buff[(int)(ptr-buff)]=neo;
    }        
    return;
}

Usage:

reeplachar(str,'s','r');


Provided that your program does really search the positions without fault (I didn't check), your question would be how do I change the contents of an object to which my pointer pch is already pointing?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜