编程在一个已知的字符串中查找最长单词,假定字符串中只含字母和空格,用空格来分隔单词。

来源:互联网 发布:vmware虚拟机网络桥接 编辑:程序博客网 时间:2024/04/26 11:33

 char str[] = "my beautiful teacher is  ";

    unsigned long  int a = 0;   //长整型变量

    a = strlen(str);

    int count = 0, max = 0 ;

    for (int i = 0; i < a; i ++) {

            if (str[i] != ' ') {

                count ++;

                continue;

            }

            max =count > max ? count : max;

            count = 0;

        }

    printf("%d\n",max);   //求最大值

    printf("最长单词为:");

    for (int i = 0; i < a; i ++) {

        if (str[i] != ' ') {

            count ++;

            if (count == max) {

                for (int j = i - max  ; j <= i ; j ++) {

                    printf("%c", str[j]);

                }

            }

            continue;

        }

        count = 0;

    }

0 0
原创粉丝点击