C语言 如何打印没有最长单词的字符串

v09wglhw  于 2022-12-17  发布在  其他
关注(0)|答案(2)|浏览(120)

我有一个代码,它打印字符串中最长的单词。
我需要它来打印这个字符串没有这个特定的字。希望你能帮助我,例如:输入:“最长单词”输出:“那个词”

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

void LongestWord(char string[100])
{
    char word[20],max[20],min[20],c;
    int i = 0, j = 0, flag = 0;
     for (i = 0; i < strlen(string); i++)
    {
        while (i < strlen(string) && string[i]!=32 && string[i]!=0)
        {
            word[j++] = string[i++];
        }
        if (j != 0)
        {
            word[j] = '\0';
            if (!flag)
            {
                flag = !flag;
                strcpy(max, word);
            }
            if (strlen(word) > strlen(max))
            {
                strcpy(max, word);
            }
            j = 0;
        }
    }
    printf("The largest word is '%s' .\n", max);

}

int main()
{
   char string[100];
    printf("Enter string: ");
    gets(string);
    LongestWord(string);
}
8ftvxx2r

8ftvxx2r1#

我尝试了一下,但我编辑了一些你已经有的东西,所以请注意评论:

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

void LongestWord(char string[100]) {
    char word[20], max[20];
    int  i = 0, j = 0;

    max[0] = '\0';  /* no more need for flag, strlen(max) == 0 */

    /* We want to store a pointer to the longest
     * word, within `string`.
     */
    const char* longest = string;

    /* we are going to put null terminators in here,
     * so let's just get this up front...
     */
    int string_length = strlen(string);

    for (i = 0; i < string_length; i++) {
        /* Save the beginning of the word. If it is
         * the longest, we will have a pointer to it.
         */
        const char* begin = &string[i];

        /* Let's use isspace so we can catch tabs
         * and line feeds as well.
         */
        while (i < string_length && !isspace(string[i]) && string[i] != 0) {
            word[j++] = string[i++];
        }
        if (i < string_length) {
            /* Put null terminators on spaces */
            string[i] = '\0';
        }
        if (j != 0) {
            word[j] = '\0';
            if (strlen(word) > strlen(max)) {
                longest = begin;
                strcpy(max, word);
            }
            j = 0;
        }
    }
    printf("The largest word is '%s' .\n", max);

    /* Loop through string and print all words,
     * unless we are on the longest word.
     */
    int len = 0;
    for (i = 0; i < 100; i += len + 1) {
        const char* it = &string[i];
        len = strlen(&string[i]);
        if (it == longest) {
            continue;
        }
        if (len == 0) {
            break;
        }
        printf("%s ", it);
    }
    puts("");
}

int main() {
    char string[100];
    printf("Enter string: ");
    fgets(string, 100, stdin);
    LongestWord(string)
}

不要使用gets。忘记它的存在。我使用的是fgetsfgets会将行结束符与字符串沿着复制,所以我改用isspace,而不是专门查找' ' (32)
我去掉了flag布尔值。这看起来像是(猜测,因为name是无用的)一个黑客,总是接受第一个单词作为最长的。与其在逻辑中间有一个黑客,不如让max成为一个0长度的字符串。然后,它总是会通过“是这个更长”的测试。
我们有了原始字符串,可以编辑它。我覆盖了'\0'的空格。现在你有了一个包含多个 embedded 字符串的数组。另外,我保存了一个指向最长单词的指针。当我们把字符串打印给用户时,我们可以只使用原始字符串。它被分成了单独的字符串,我们可以一个接一个地打印。当我们到达最长单词时,longest将指向与&string[i]相同的位置。我们需要做的就是跳过这一步...

7y4bm7vi

7y4bm7vi2#

另一个需要考虑的版本。尝试使用更少的变量。

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

void func( char *phrase ) {
    // declare some variables and make a copy of the phrase for chopping-up
    char *cpy = strdup( phrase ), *plw = NULL, *cp;
    int len, max = 0;

    // use strtok() to isolate words in the copy, measure lengths, remember longest
    for( cp = cpy; (cp = strtok( cp, " \t\n" ) ) != NULL; cp = NULL )
        if( ( len = strlen( cp ) ) > max )
            plw = cp, max = len;

    // deal with string (original buffer) beyond the longest word
    char *rest = phrase + (plw - cpy) + max;
    if( *rest ) {
        while( isspace( *rest) ) rest++; // skip over spaces
        if( ( cp = strchr( rest, '\n' ) ) != NULL ) // clobber original LF
            *cp = '\0';
    }

    // print longest from copy, then pre-/post-amble from original
    printf( "Phrase: '%s'\n", phrase );
    printf( "Longest word: '%s'\n", plw );
    printf( "Phrase now: '%.*s%s'\n", plw - cpy, phrase, rest );

    free( cpy ); // tidy up
}

int main( void ) {
    char phrase[ 256 ] = "The long and winding road\n";

    // printf( "Enter a phrase: ");
    // fgets( string, sizeof phrase, stdin );

    func( phrase );

    return 0;
}
Phrase: 'The long and winding road'
Longest word: 'winding'
Phrase now: 'The long and road'

编辑

最好使用标准库函数,而不是试图重新发明可用的功能(因为不熟悉)。
下面是上面的func()的一个更短的版本,处理零散的空格作为一个练习。

void func( char *phrase ) {
    char *cp = phrase, *plw = NULL;
    int lwLen = 0;

    while( *cp && *cp != '\n' ) {
        char *bp = cp += strspn( cp, " \t" ); // skip over whitespace
        cp += strcspn( cp, " \t\n" ); // skip over non-whitespace
        if( cp - bp > lwLen )
            lwLen = cp - (plw = bp);
    }
    *cp = '\0';

    printf( "Phrase: '%s'\n", phrase );
    printf( "Longest word: '%.*s'\n", lwLen, plw );
    printf( "Phrase now: '%.*s%s'\n\n", plw-phrase, phrase, plw + lwLen );
}

相关问题