tags:

views:

69

answers:

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

+2  A: 

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');
Steve Jessop
@Steve Jessop: yes that is what I am looking for thank you. It de-references to the character it is pointing to in the string and replaces the character with the new character.
Tommy
+1  A: 
void reeplachar(char *buff, char old, char niu)
{
 char *ptr;
 for(;;)
 {
  ptr = strchr(buff, old);
  if(ptr==NULL) break; 
     buff[(int)(ptr-buff)]=niu;
 }
 return;
}

Usage:

reeplachar(str,'s','r');
Hernán Eche
@Hernán Eche: Ok I was curious how to get the index from the pointer, so you type cast it to int with: (int)(ptr-buff) ?
Tommy
@Tommy yes, those are the indexes, if you want them all, need a new int array to store in
Hernán Eche
A: 

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?

Jens Gustedt
+1  A: 

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'));
paxdiablo