
按照题目指定的要求,编写两个函数,一个函数用来读入表示颜色的字符串以井字号做术,另外一个函数就是在已有的字符串数组中查找长度最长的那个字符串。下面是代码和运行的截图。
#include
#include
#include
int read_color(char **color)
char **find_max_len(const char **s, int n)
int main()
{ int n//字符串个数
char *color[150], **ans
n = read_color(color)//读入字符串,并把字符串的首地址存入指针数组color[],返回数组的长度
ans = find_max_len(color, n)//查找最长的单词,返回指向第一个最长单词的指针数组元素的指针
printf("%s\n", *ans)
return 0
}
int read_color(char **color)
{ int i=0
do
{ color[i]=(char*)malloc(150)
scanf("%s",color[i])
}
while(strcmp(color[i++],"#"))
return i
}
char **find_max_len(const char **s, int n)
{int i,max=0
for(i=1i<ni++)
if(strlen(s[i])>strlen(s[max]))max=i
return &s[max]
}
#include<stdio.h>
#include<string.h>
int main()
{
char str[100]
gets(str)
void findLongest(char str[])
findLongest(str)
return 0
}
void findLongest(char str[])
{
int currLen=0,maxLen=0,currStart=0,MaxStart=0
int i=0,j=0
for(i=0str[i]i++)
{
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))
{
if(currLen==0)//当前长度等于0时,说明一个单词刚刚查找完,此时的位置为
currStart=i//新单词的开始位置
currLen++
}
if(currLen>maxLen)//当前单词的长度大于最大值,进行赋值
{
maxLen = currLen
MaxStart = currStart
}
if(str[i]==' ')//遇到空格,即一个单词已经结束。
{
currLen = 0
}
}
for(j=MaxStartj<MaxStart+maxLenj++)
printf("%c",str[j])
}
运行效果:
扩展资料:Return用法
1.含义:return表示从被调函数返回到主调函数继续执行,返回时可附带一个返回值,返回值可以是一个常量,变量,或是表达式。
2.作用:结束正在运行的函数,并返回函数值。
3.返回值:
计算结果表示函数执行的顺利与否(-1、0)返回值可以为各种数据类型,如:int,float,ouble,char,a[](数组),*a(指针),
结构或类(c++)返回类型规定了return后面所加的量的类型,如果返回类型声明为void,则不需要返回值。public static void Main()//程序入口只可以声明为void和int的返回
{
//不需要返回值就OK
}
public static void mm()
{
return//有些时候,在void的方法中,你需要跳出它,可以直接用return而不能加任何量在后面
}
public static int cc()
{
return 321//因为返回类型声明为int,所以返回一个整数
}
public static string msmsm()
{
return“asdfhasjghdg”//因为返回类型声明为string,所以返回一个字符串
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)