最长单词 (分割字符串)(蓝桥杯-算法提高)

编写一个函数,输入一行字符,将此字符串中最长的单词输出。 
输入仅一行,多个单词,每个单词间用一个空格隔开。单词仅由小写字母组成。所有单词的长度和不超过100000。如有多个最长单词,输出最先出现的。

Input

Output

Sample Input

copy
I am a student

Sample Output

copy
student


int main()
{
    string my_string;
    while(getline(cin, my_string, '\n'))
    {
        char *pch,*p;
        char str[100000+5];
        strcpy(str, my_string.c_str());
        pch = strtok(str, " ");
        k=0;
        while(pch != NULL)
        {
            if(strlen(pch)>k)
            {
                p=pch;
                k=strlen(pch);
            }
            //cout << pch << endl;
            pch = strtok(NULL, " ");  // 注意这里是NULL
        }
        cout<<p<<endl;
    }
    ok;
}

 

posted @ 2019-09-18 09:06  __MEET  阅读(381)  评论(0编辑  收藏  举报