簡體   English   中英

使用遞歸計算c中的單詞(字符串)中字母出現的次數

[英]Count the number of times a letter occurs in a word(string) in c using recursion

這是我在com sci實驗室中的決賽,我想知道main函數是否正確,所以我剛剛添加了另一個函數,因為idk如何使用字符串中的遞歸來計算此字符出現的次數。很難。 請幫我。 :)

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

int count_chars(const char* string, char ch);


int main()
{
    char string[BUFSIZ];
    char ch[2];
    int count;

    printf ("Please enter a line of text, max %d characters\n", sizeof(string));

    if (fgets(string, sizeof(string), stdin) != NULL)
        printf ("You entered: %s\n", string);

    printf("Input the letter you want to be counted: ");
    gets(ch);

    count=count_chars(const char* string, char ch);
    printf("The number of times the letter occurs in the word above is: %d", count);

    return 0;
}


int count_chars(const char* string, char ch)
{
    int count = 0;

    for(; *string; count += (*string++ == ch)) ;
    return count;
}

例如; 輸入為:“ aabbabc”,那么您需要查找的字符為b,因此程序應按以下方式運行:(這是給我的提示),但他說您應該將其轉換為(函數?)我試過了,不起作用。

"b"  "aabbabc"
if 'b'==st[0]
1+cnt('b', "abbabc");
else 
cnt('b' , "abbabc");

這將起作用:

int count_chars(const char* string, char ch) {
  return *string? count_chars(string + 1, ch) + (ch == *string) : 0;
}

您的遞歸函數應該像所有遞歸函數一樣工作。 你需要:

  1. 一個基本案例(停止遞歸)
  2. 減少的輸入集(從原始輸入縮水,以便實際達到基本情況)

您的函數將如下所示(使用偽代碼)

function count_chars(string s, char ch){
   int count = 0 

   if (s is empty) {
        return 0
    }

    char head = extract first char of s
    string remainder = get rest of s without the head
    if (head == ch) {
        count = 1
    }
    return count + count_chars(remainder, ch)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM