最长的字符串

版权声明:本文为博主原创,未经博主允许不得转载 https://blog.csdn.net/Sherry_Yue/article/details/85635098

【问题描述】
找出最长的字符串。输入5个字符串,输出其中最长的字符串。输入字符串调用函数scanf("%s",sx)。如果最长的字符串有多个,则打印第一个。请自行设计int StrLength(char *)函数,求解字符串长度,不允许调用系统函数。

【输入形式】
首先打印提示"Input 5 srings:";然后直接在冒号后面输入五个字符串,每个字符串之间用空格或回车或制表符隔开。

【输出形式】
首先打印"The longest is:";紧跟后面输出最长的一个字符串;换行。

【运行时的输入输出样例】
Input 5 srings:li
wang
zhang
jin
xian
The longest is:zhang

#include <iostream>
#include <stdio.h>
using namespace std;

int StrLength(char *);//求解字符串长度

int main()
{
    char name[5][100];
    int len[5];
    cout << "Input 5 strings:";
    for(int i=0;i<5;++i)
    {
        scanf("%s",name[i]);
        len[i] = StrLength(name[i]);
    }
    int Max = len[0];
    int index = 0;
    for(int i=1;i<5;++i)
        if(Max<len[i])
        {
            Max = len[i];
            index = i;
        }
    cout << "The longest is:" << name[index] << endl;
    return 0;
}

int StrLength(char * name)
{
    int len = 0;
    for(int i=0;name[i]!='\0';++i,++len);
    return len;
}

猜你喜欢

转载自blog.csdn.net/Sherry_Yue/article/details/85635098