Question 4: Please write a function void fun(char *tt, int pp[]), count the number of occurrences of the 26 letters "a" to "z" in the tt string, and place them in the array indicated by pp in turn middle.

Please add a picture description

C test questions

Question 4请编写一个函数void fun(char *tt,int pp[]),统计在tt字符串中“a”到“z”26个字母各自出现的次数,并依次放在pp所指数组中。

ChatGPT answers as follows:

The following knowledge points were mainly investigated:

  1. Basic operations on strings : In C language, strings are stored in the form of character arrays, and strings can be manipulated through pointers. In this question, we need to use strlenthe function to calculate the length of the string, and use the array subscript to traverse each character in the string.

  2. Use of arrays : In C language, an array is a commonly used data structure that can be used to store a set of data of the same type. In this question, we need to define an integer array with a length of 26 ppto store the counter of the number of occurrences of each letter.

  3. Use of pointers : In C language, a pointer is a very important data type, which can be used to store the address of a variable, and can also be used to access array elements. In this problem, we need to ttpass the pointer to the string to the function and use the pointer inside the function to access each character in the string.

  4. Use of conditional statements : In C language, conditional statements can be used to control the flow of the program and execute different code blocks according to different conditions. In this question, we need to use ifthe statement to determine whether the current character is a lowercase letter, and if so, add 1 to the counter at the corresponding position.

In short, this question examines some basic grammar and data structures in the C language, and requires a certain grasp of these knowledge points to solve the problem.

The problem-solving idea of ​​the program:

The problem-solving idea of ​​this program is relatively simple, mainly divided into the following steps:

  1. Define an integer array with a length of 26 ppto store the counter of the number of occurrences of each letter.

  2. Define a pointer to a string ttto access each character in the string.

  3. Use strlenthe function to calculate the length of a string to get the total number of characters in the string.

  4. Use forto loop through each character in the string, if the current character is a lowercase letter, add 1 to the counter at the corresponding position.

  5. Store the value of the number of occurrences of each letter in the counter array ppin alphabetical order.

After the program executes the above steps, we can get the statistical results of the number of occurrences of each letter in the string.

In the main function, we can first define a string strand a counter array count, and then pass the string and counter array to funthe function as parameters to get the statistical results. Finally, we can use to forloop through the counter array and output the statistical results of the number of occurrences of each letter to the console.

Solution 1: loop traversal method, implemented code:

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

void fun(char *tt, int pp[]) {
    
    
    int i, len;
    len = strlen(tt);
    for (i = 0; i < len; i++) {
    
    
        if (tt[i] >= 'a' && tt[i] <= 'z') {
    
    
            pp[tt[i] - 'a']++;
        }
    }
}

int main() {
    
    
    char str[] = "hello world";
    int count[26] = {
    
    0};
    fun(str, count);
    for (int i = 0; i < 26; i++) {
    
    
        printf("%c: %d\n", 'a' + i, count[i]);
    }
    return 0;
}

The parameters of this function include a pointer to a string ttand an array of integers pp. Inside the function, we first calculate the length of the string lenand then iterate over each character in the string. If the current character is a lowercase letter, add 1 to the counter at the corresponding position. Finally, the function will store the value of the number of occurrences of each letter in the counter array ppin alphabetical order.

You can pass the string to be counted as a parameter when calling the function.

Here we count the number of occurrences of each letter in the string "hello world", and output the result to the console.

Of course, there are other C language code implementations.

Solution 2: Use the recursive method to implement the code:

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

void fun(char *tt, int pp[]) {
    
    
    if (*tt == '\0') {
    
     // 递归结束条件
        return;
    }
    if (*tt >= 'a' && *tt <= 'z') {
    
     // 判断字符是否为小写字母
        pp[*tt - 'a']++; // 统计出现次数
    }
    fun(tt + 1, pp); // 递归处理下一个字符
}

int main() {
    
    
    char tt[] = "hello world";
    int pp[26] = {
    
    0};
    fun(tt, pp);
    for (int i = 0; i < 26; i++) {
    
    
        printf("%c: %d\n", 'a' + i, pp[i]);
    }
    return 0;
}

funThe parameter of the function ttis a pointer to a string and ppa pointer to an array of integers. The implementation idea of ​​the function is to recursively traverse each character in the string, and if the character is a lowercase letter, add 1 to the corresponding counter. Finally, iterate through the counter array and output the number of occurrences of each letter.

In the main function, we define a string ttand an array of counters ppand pass them as parameters to the function fun. Finally, output the number of occurrences of each letter in the counter array.

Hope this code helps you!

Solution 3: Use pointers, code implementation:

void fun(char *tt, int pp[]) {
    
    
    // 初始化pp数组
    for (int i = 0; i < 26; i++) {
    
    
        pp[i] = 0;
    }
    // 遍历tt字符串,统计每个字母出现次数
    while (*tt != '\0') {
    
    
        if (*tt >= 'a' && *tt <= 'z') {
    
    
            pp[*tt - 'a']++;
        }
        tt++;
    }
}

int main() {
    
    
    char str[] = "hello world";
    int count[26] = {
    
    0};
    fun(str, count);
    for (int i = 0; i < 26; i++) {
    
    
        printf("%c: %d\n", 'a' + i, count[i]);
    }
    return 0;
}

The implementation of this function is very simple. First, initialize the pp array, and then traverse the tt string. If the current character is a lowercase letter, add 1 to the corresponding pp array element. Among them, *ttthe character pointed to by the pointer tt *tt++means that the current character is taken out first, and then the pointer tt points to the next character. Finally, the value of each element in the pp array is the number of times the 26 letters appear in the tt string.

Note that this function assumes that the input tt string only contains lowercase letters. If the input string contains other characters, it may cause program errors. If you need to process other characters, you can add corresponding judgment logic to the function.

Solution 4: Use dynamic memory, code implementation:

void fun(char *tt, int pp[]) {
    
    
    // 动态分配内存,用于存储每个字母的出现次数
    int *counts = (int*)malloc(26 * sizeof(int));
    if (counts == NULL) {
    
    
        printf("Error: failed to allocate memory.\n");
        return;
    }
    // 初始化counts数组
    for (int i = 0; i < 26; i++) {
    
    
        counts[i] = 0;
    }
    // 遍历tt字符串,统计每个字母出现次数
    while (*tt != '\0') {
    
    
        if (*tt >= 'a' && *tt <= 'z') {
    
    
            counts[*tt - 'a']++;
        }
        tt++;
    }
    // 把counts数组中的值复制到pp数组中
    memcpy(pp, counts, 26 * sizeof(int));
    // 释放动态分配的内存
    free(counts);
}

This function is similar to the previous one, except that it uses dynamic memory allocation to store the number of occurrences of each letter. First, malloca function is used to dynamically allocate an integer array of size 26 countsto store the number of occurrences of each letter. If memory allocation fails, the function outputs an error message and returns. Then, traverse the tt string, count the number of occurrences of each letter, and store the result in countsan array. Finally, use memcpya function to countscopy the values ​​in the array into ppthe array, and then free the dynamically allocated memory.

It should be noted that after using malloca function to dynamically allocate memory, the function must be used to release the memory after use freeto avoid memory leaks.

If you are satisfied with the answer, please correct me.

Guess you like

Origin blog.csdn.net/zp1990412/article/details/130722299
TT