繁体   English   中英

如何在 c 程序的 function 定义中定义“strchr(s,oldch)”?

[英]How to define "strchr(s,oldch)" in function definition in c program?

我是 C 语言的初学者。 我不明白 function 定义部分。 “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))是什么意思? 它做什么工作? 其他方式怎么写? 谁能解释一下?

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

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

句法:

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() function 的用法。

#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|

C 库 function 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM