Letter Olympiad 1149: The Longest Word 2

【Description】

A simple English sentence ending with '.', words are separated by spaces, without abbreviations and other special forms.

【enter】

A simple English sentence ending with '.' (length no more than 500), words are separated by spaces, without abbreviations and other special forms.

【Output】

The longest word in the sentence. If more than one, output the first one.

【Input example】

I am a student of Peking University.

【Example of output】

University

Not much to say, just go to the code.

C++:
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s1,s2,s3;  //三个string类的字符串类型
    int count=0;     //用来比较单词的长度
    do
    {
        cin>>s1;    
        s3=s1;         //借助第三方
        if(s3[s3.size()-1]=='.')     //遇到带有.的单词时抹去
                s3[s3.size()-1]='\0';
        if(s3.size()>count)   //比较单词长度
        {            
            s2=s3;               
            count=s3.size();
        }               
    }while(s1[s1.size()-1]!='.');  //知道最后一个单词的最后出现.
    cout<<s2;      
}
C language:
#include<stdio.h>
#include<string.h>
int main()
{
    char c[501];     
    fgets(c,501,stdin);  //使用fgets()来输入字符串
    /*gets(c);   */       //因为gets()输入不安全所以建议少用,现在用gest输入在信奥赛中是无法通过的                
    int count=0;         //计算每个单词的长度
    int max=0;           //表示最长单词的长度
    int pos1,pos2;           //pos1表示单词的起始位置,pos2表示单词的末位置
    for(int i=0;i<strlen(c);i++)  //循环遍历
    {
        if(c[i]!=' '&&c[i]!='.') //没遇到空格或者.的时候就表示是同一个单词
            count++;
        else                      
        {
            if(count>max)     //如果该单词的长度大于max
            {
                max=count;      //重新初始化max
                pos1=i-count;    //寻找该单词的初始位置
                pos2=i-1;      //寻找末位置
            }
            count=0;      //赋值为0开始下一个单词的长度计数
        }
    }
    for(int i=pos1;i<=pos2;i++) 
        printf("%c",c[i]);        //输出第一次出现的最长的单词
}

Well, this question is over! Here, I suggest that you learn C++ while learning C. When encountering character problems, using C++ can solve it faster and more conveniently!

Guess you like

Origin blog.csdn.net/H1727548/article/details/129635057