-1

我是 C 语言的初学者。我不明白函数定义部分。“strchr(s,oldch)”有什么作用?我正在尝试将其转换为 ctypes 程序。

#include <stdio.h>
#include <string.h>
#include <math.h>

/* Replace och with nch in s and return the number of replacements */
extern int replace(char *s, char och, char nch);

/* Replace a character in a string */
int replace(char *s, char oldch, char newch) {
int nrep = 0;
while (s = strchr(s,oldch)) {
*(s++) = newch;
nrep++;
}
return nrep;
}

/* Test the replace() function */
{
char s[] = "Skipping along unaware of the unspeakable peril.";
int nrep;
nrep = replace(s,' ','-');
printf("%d\n", nrep);
printf("%s\n",s);
}

是什么while (s = strchr(s,oldch))意思?它做什么工作?其他方式怎么写?谁能解释一下?

4

2 回答 2

1

C 库函数 char在参数指向的字符串中strchr(const char *str, int c)搜索第一次出现的字符(无符号字符) 。cstr

strchr()函数检查原始字符串是否包含定义的字符。如果在字符串中找到该字符,则返回一个指针值;否则,它返回一个空指针。

句法:

char *strchr(const char *str, int c)

参数

str − This is the C string to be scanned.
c − This is the character to be searched in str.

例子。下面的例子展示了strchr()函数的用法。

#include <stdio.h>
#include <string.h>

int main () {
   const char str[] = "www.ted.com";
   const char ch = '.';
   char *ret;

   ret = strchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}

编译并运行上述程序,将产生以下结果:

String after |.| is - |.ted.com|
于 2021-11-26T13:51:40.740 回答
0

C 库函数 strchr 循环遍历字符数组并返回某个字符的第一次出现。在您的情况下,您正在遍历一个字符数组(字符串)并将oldch替换为newch,然后您将返回字符串中替换的字符总数:-

/*  
    Declaring a function called replace that takes as input 3 
    arguments:- 
    > a string 's',
    > character to be replaced in the string 'och'
    > what to replace with 'nch'
*/
extern int replace(char *s, char och, char nch);

int replace(char *s, char oldch, char newch) {
    //initialize our counter to keep track of characters replaced
    int nrep = 0;
    /*
      call the function strchr and try to find if the next position of 
      the character we'd like to replace can be located, i.e. there's 
      still more old characters left in the string. If this is the 
      case, replace this character with 'newch' and continue doing this 
      until no more old characters can be found in the string, at which 
      point you return total number of old characters replaced (nrep).
    */
    while (s = strchr(s,oldch)) {
        //replace current oldch with newch and find next oldch
        *(s++) = newch;
        //increment number of characters replaced
        nrep++;
    }
    return nrep;
}
于 2021-11-21T05:25:33.017 回答