Ⅰ C語言編程:輸出由鍵盤輸入的n個字元串中最長的字元串。咋做
代碼文本:
#include "stdio.h"
#include <stdlib.h>
#include <string.h>
#define N 101
int Longer(char **str,int n){//判斷串長度函數
int i,k;
for(k=0,i=1;i<n;i++)
if(strlen(str[i])>strlen(str[k]))
k=i;
return k;
}
int main(int argc,char *argv[]){
int n,i;
char **str,*q;
printf("Enter n(int n>0)... ");
if(scanf("%d",&n)==1 && n>0){//輸入字元串個數n
q=(char *)malloc(sizeof(char)*N*n);//由n申請空間
if(!q || (str=(char **)malloc(sizeof(char *)*n))==NULL){
printf("Application memory failure, exit... ");
return 0;//申請不成功則退出
}
for(str[i=0]=q;i<n;str[i++]=q+i*N);//將空間組織成二維數組
printf("Please enter %d string(s)... ",n);
for(i=0;i<n;scanf("%100s",str[i++]));//輸入字元串
printf(" The longest: %s ",str[Longer(str,n)]);//輸出
free(q);//釋放所申請的空間
free(str);
}
else
printf("Input error, exit... ");//輸入錯誤提示
return 0;
}
Ⅱ C語言 輸出最長字元串問題
你longest函數,當判斷當前單詞比前一個單詞短的時候,你沒有將len置0,導致後一個單詞len累加了。
我修改的地方標注了,把len++拉到判斷外面執行就行。
#include<stdio.h>
#include<string.h>
intmain()
{
intalphabetic(char);
intlongest(char[]);
inti;
charline[100];
printf("請輸入一個字元串:
");
gets(line);
printf("最長的單詞是:");
for(i=longest(line);alphabetic(line[i]);i++)
printf("%c",line[i]);
printf("
");
return0;
}
intalphabetic(charc)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
return1;
else
return0;
}
intlongest(charstr[])
{
intlen=0,i,lenght=0,flag=1,place=0,point;
for(i=0;i<=strlen(str);i++)
if(alphabetic(str[i]))
if(flag)
{
point=i;
flag=0;
}
else
len++;
else
{
flag=1;
if(len>=lenght)
{
lenght=len;
place=point;
}
len=0;//修改這個地方!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
return(place);
}
Ⅲ C語言:從鍵盤輸入10個字元串,找出一個最長的字元串。
先輸入10個字元串,然後依次計算字元串長度,找到最長的一個,並把這個字元串輸出即可。
代碼如下:
#include<stdio.h>
#include<string.h>
intmain()
{
chars[10][100];
inti;
intmax_i,max_len=0;
for(i=0;i<10;i++)
scanf("%s",a[i]);//輸入10個字元串。
for(i=0;i<10;i++)
{
intl=strlen(s[i]);
if(max_len<l)//依次將長度和max_len對比,找到最長一個。
{
max_len=l;
max_i=i;
}
}
printf("%s ",s[max_i]);//輸出最長字元串。
return0;
}