c语言函数的数组 c语言函数中数组的使用( 三 )


输入一个字符串 。
#include"stdio.h"
main()
{
char st[15];
printf("input string:\n");
gets;
puts;
}
tips:gets函数并不以空格作为字符串输入结束的标志,而只是以回车作为输入
结束 , 这是与scanf不同的部分
3)字符串连接函数strcat 格式:strcat(字符数组名1 , 字符数组名2)
功能:把字符数组2中的字符串连接到字符数组1中字符串后面,并删去字符串
1后的串标志"\0",本函数返回字符数组1的首地址 。
#include"string.h"
main()
{
static char st1[30]="My name is ";
int st2[10];
printf("input your name:\n");
gets(st2);
strcat(st1,st2);
puts(st1);
}
4)字符串拷贝函数strcpy 格式:strcpy(字符数组名1,字符数组名2)
功能:把字符数组2中的字符串拷贝到字符数组1中,串结束标志 "\0"也一同
拷贝 , 字符数组2也可以是一个字符常量 , 就相当于把一个字符串赋予一个字符数组
#include"string.h"
main()
{
static char st1[15],st2[]="C Language";
strcpy(st1,st2);
puts(st1);
printf("\n");
}
5)字符串比较函数strcmp格式:strcmp(字符数组1,字符数组2) 功能:
按照ASCII码顺序比较两个数组中的字符串,并有函数返回值返回比较结果
#include"string.h"
main()
{
int k;
static char st1[15],st2[]="C Language";
printf("input a string:\n");
gets(st1);
k=strcmp(st1,st2);
if(k==0) printf("st1=st2\n");
if(k0) printf("st1st2\n");
if(k0) printf("st1st2\n");
}
6)测字符串长度的函数strlen 格式:strlen(字符数组名) 功能:
测字符串的实际长度(不含字符串结束标志"\0")并作为函数返回值
#include"string.h"
main()
{
int k;
static char st[]="C Language";
k=strlen;
printf("The lenth of the string is %d\n",k);
}
程序举例:
例一:
main()
{
int i,j,p,q,s,n,a[11]={127,3,6,28,54,68,87,105,162,18};
for(i=0;i10;i++)
{
p=i;q=a[i];
for(j=i+1;j10;j++)
if(qa[j]) {p=j;q=a[j];}
if(p!=i)
{
s=a[i];
a[i]=a[p];
a[p]=s;
}
printf("%d",a[i]);
}
printf("\ninput number:\n");
scanf("%d",n);
for(i=0;i10;i++)
if(na[i])
{for(s=9;s=i;s--) a[s+1]=a[s];brbreak;}
a[i]=n;
for(i=0;i10;i++)
printf("%d",a[i]);
printf("\n");
}
例二:
main()
{
static int a[][4]={3,16,87,65,4,32,11,108,10,25,12,27};
int b[3],i,j,l;
for(i=0;i=2;i++)
{
l=a[i][0];
for(j=1;j=3;j++)
if(a[i][j]l) l=a[i][j];
b[i]=l;
}
printf("\narray a:\n");
for(i=0;i=2;i++)
{
for(j=0;j=3;j++)
printf("%5d",a[i][j]);
printf("\n");
}
printf("\narray b:\n");
for(i=0;i3;i++)
printf("%5d",b[i]);
printf("\n");
}
例三:
void main()
{
char st[20],cs[5][20];
int i,j,p;
printf("input country's name:\n");
for(i=0;i5;i++)
gets(cs[i]);
printf("\n");
for(i=0;i5;i++)
{
p=i;strcpy(st,cs[i]);
for(j=i+1;j5;j++)
if(strcmp(cs[j],st)0) {p=j;strcpy(st,cs[j]);}
if(p!=i)
{strcpy(st,cs[i]);brstrcpy(cs[i],cs[p]);brstrcpy(cs[p],st);br}
puts(cs[i]);
printf("\n");
C语言中自定义的函数中有数组,应该如何运用该函数方法
有2
将该数组定义为全局变量,即:
int
g_arr;
void
fun()
{...}
void
main()
{...}
2.将该数组作为函数参数传递到自定义函数里,即:

推荐阅读