簡體   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