如何使用strchr替换此示例中的字符?

时间:2010-09-22 18:26:57

标签: 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;
}

我如何索引str,以便用'r'替换每个's'。

感谢。

4 个答案:

答案 0 :(得分:9)

您不需要索引字符串。你有一个指向你想要改变的角色的指针,所以通过指针分配:

*pch = 'r';

但是,一般情况下,您使用[]进行索引:

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

答案 1 :(得分:3)

您可以使用以下功能:

char *chngChar (char *str, char oldChar, char newChar) {
    char *strPtr = str;
    while ((strPtr = strchr (strPtr, oldChar)) != NULL)
        *strPtr++ = newChar;
    return str;
}

它只是遍历字符串查找特定字符并将其替换为新字符。每次通过(和你的一样),它从超出前一个字符的地址开始,以便不重新检查已经检查过的字符。

它还返回字符串的地址,这是一个经常使用的技巧,因此您也可以使用返回值,例如:

printf ("%s\n", chngChar (myName, 'p', 'P'));

答案 2 :(得分:1)

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

答案 3 :(得分:0)

如果您的程序确实搜索了没有错误的位置(我没有检查),那么您的问题是如何更改指针pch已经指向的对象的内容?