How to replace the character in this example with 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 at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}

How would I index str so that I replace all 's' with 'r'.

Thank.

+5
source share
4 answers

You do not need to index the row. You have a pointer to the character you want to change, so assign it with a pointer:

*pch = 'r';

In general, you index with []:

ptrdiff_t idx = pch - str;
assert(str[idx] == 's');
+9
source

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 a string that looks for a specific character and replaces it with a new character. Each time through (like yours) it starts with the address following the previous character, so as not to double-check the characters that have already been verified.

, , , :

printf ("%s\n", chngChar (myName, 'p', 'P'));
+3
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;
}

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

Provided that your program is really looking for positions without failures (I did not check), your question is how to change the contents of the object that my pointer already points to pch?

0
source

All Articles