简体   繁体   English

最长的字符串

[英]The longest string

I'm going through K&R C programming language book and try to solve all the exercises. 我正在阅读K&R C编程语言书并尝试解决所有练习。

There is a sample program that finds the longest string in the input. 有一个示例程序可以在输入中找到最长的字符串。 It basically reads strings from input one by one and store the longest in the array with pre-defined length. 它基本上从输入中逐个读取字符串,并以预定义的长度存储在数组中最长的字符串。 In other words it assumes the upper bound on the length of the longest string. 换句话说,它假定最长字符串长度的上限。

After this program there is an exercise that asks to change the program such that it does not assume the bound on the length. 在此程序之后,有一个练习要求更改程序,使其不承担长度的约束。 I have no idea how to achieve this without using dynamic memory allocation (which is discussed in the following chapters of the book). 我不知道如何在不使用动态内存分配的情况下实现这一点(本书后面的章节对此进行了讨论)。

If I'm correct, arrays in C are defined during the compilation so their length is static unless we allocate memory dynamically. 如果我是正确的,在编译期间定义C中的数组,因此除非我们动态分配内存,否则它们的长度是静态的。

I'm assuming you are referring to exercise 1.16 on page 30. The complete statement is 我假设你指的是第30页的练习1.16。完整的陈述是

Exercise 1-16. 练习1-16。 Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text. 修改最长行程序的主程序,以便正确打印任意长输入行的长度,并尽可能多地打印文本。

It is impossible to return the whole string if its length is arbitrary, because you would have to store it, and that would require dynamic memory allocation. 如果长度是任意的,则无法返回整个字符串,因为您必须存储它,这将需要动态内存分配。 However, you can slightly modify the main routine so it will correctly compute the length of the string, and output "as much as possible" of the text, ie up to a fixed length. 但是,您可以稍微修改主例程,以便正确计算字符串的长度,并输出“尽可能多”的文本,即最多固定长度。

Here is one possible answer: 这是一个可能的答案:

#define MAXLINE 1000 /* maximum input line size */

main() {
    int buf_len; /* current buffer length (<= MAXLINE) */
    int len = 0; /* current full line length */
    int max = 0; /* maximum length seen so far */
    char buffer[MAXLINE];  /* current input line */
    char line[MAXLINE];    /* prefix of longest-line candidate */
    char longest[MAXLINE]; /* longest line saved here */

    while ((buf_len = getline(buffer, MAXLINE)) > 0) {
        if (len == 0) /* this is the first chunk of the string */
            copy(line, buffer);
        len += buf_len;
        if (buf_len < MAXLINE || buffer[MAXLINE-2] == '\n') {
            /* the string was terminated */
            if (len > max) {
                max = len;
                copy(longest, line);
            }
            /* this line was fully processed */
            /* now reset len to 0 and process the next string */
            len = 0;
        }
    }
    if (max > 0)
        printf("%s", longest);
    return 0;
}

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

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