Ⅰ C语言为什么要写多个函数,有什么好处
现在刚学练习写程序是练习语法,看不出优越性。
主要体现在:
1、以后编写相对大型的代码或者课程设计作业,多次需要同一种功能(比如对数据的输出或者计算某种数据结构的长度等),那么你可以在需要的时候再main函数插入同样的一段代码也就是敲上同样的或者仅有几个参数差别的代码。这样,是好看了,但是代码长度太长了,显得比较冗杂又占用空间。所以呢,对这种多次使用的功能单独编写成一个函数,那些可能仅仅一个或者几个参数不一样的情况就作为形参实参了。
2、代码可读性好。没一个函数功能独立,都是实现自己的一种预定的功能。方便编程者阅读。
Ⅱ C语言如何分割字符串
可以写一个分割函数,用于分割指令,比如cat a.c最后会被分割成cat和a.c两个字符串、mv a.c b.c最后会被分割成mv和a.c和b.c三个字符串。
参考代码如下:
#include<stdio.h>
#include<string.h>
#defineMAX_LEN128
voidmain()
{
inti,length,ct=0,start=-1;
charinputBuffer[MAX_LEN],*args[MAX_LEN];
strcpy(inputBuffer,"mva.cb.c");
length=strlen(inputBuffer);
for(i=0;i<=length;i++){
switch(inputBuffer[i]){
case'':
case' ':/*argumentseparators*/
if(start!=-1){
args[ct]=&inputBuffer[start];/*setuppointer*/
ct++;
}
inputBuffer[i]='';/*addanullchar;makeaCstring*/
start=-1;
break;
case'':/*shouldbethefinalcharexamined*/
if(start!=-1){
args[ct]=&inputBuffer[start];
ct++;
}
inputBuffer[i]='';
args[ct]=NULL;/*nomoreargumentstothiscommand*/
break;
default:/*someothercharacter*/
if(start==-1)
start=i;
}
}
printf("分解之后的字符串为: ");
for(i=0;i<ct;i++)
printf("%s ",args[i]);
}
Ⅲ C语言函数字符串截取分割
C标准库中提供了一个字符串分割函数strtok();
实现代码如下:
#include<stdio.h>
#include<string.h>
#defineMAXSIZE1024
intmain(intargc,char*argv[])
{
chardates[MAXSIZE]="$GPGGA,045950.00,A,3958.46258,N,11620.55662,E,0.115,,070511,,,A*76";
char*delim=",";
char*p;
printf("%s",strtok(dates,delim));
while(p=strtok(NULL,delim))
{
printf("%s",p);
}
printf(" ");
return0;
}
运行结果截图如下:
Ⅳ C语言中字符切割函数split的实现
#include<stdio.h>
#include<string.h>
//将str字符以spl分割,存于dst中,并返回子字符串数量
intsplit(chardst[][80],char*str,constchar*spl)
{
intn=0;
char*result=NULL;
result=strtok(str,spl);
while(result!=NULL)
{
strcpy(dst[n++],result);
result=strtok(NULL,spl);
}
returnn;
}
intmain()
{
charstr[]="whatisyouname?";
chardst[10][80];
intcnt=split(dst,str,"");
for(inti=0;i<cnt;i++)
puts(dst[i]);
return0;
}