字符数组的输入与输出

来源:互联网 发布:黑客帝国文字矩阵 编辑:程序博客网 时间:2024/06/06 09:34
  • 字符输入输出有两种办法。一是用”%c’’输入输出一个字符,二是,用“%s”将字符串一次输入或输出。
  • scanf函数中的输入项如果是字符数组名,就不加地址符“&”。

    字符串处理函数

puts gets strcat strcpy strncpy strcmp strlen strlwr strupr 一般形式 puts(字符数组) gets(字符数组) strcat(字符数组1,字符数组2) strcpy(字符数组1,字符数组2) strncpy(字符数组1,字符数组2) strcmp(字符串1,字符串2) strlen(字符数组) strlwr(字符串) strupr(字符串) 作用 输出一个字符串,作用相当于printf 输入一个字符串,作用相当于scanf 将两个字符串连接起来,字符串2接到字符串1后。 strcpy将字符串2中字符复制到字符串1中,strncpy可以把字符串2中的前n个字符复制到字符串1中。 对两个字符串从左到右一个一个比较(ASCLL码值大小的比较)直到出现不同字符或遇到“\0”结束,遇到不同的字符时,按第一个不同的字符的比较结果为准。 计算出字符串中有几个字符 将字符串中的大写字母转换成小写字母 将字符串中的大写字母转换成小写字母。

puts and gets函数

#include<stdio.h>int main(){    char str[10];    gets(str);    puts(str);}

strcat

#include<stdio.h>int main(){   char str1[30]={"People's Republic of "};   char str2[]={"China"};   printf("%s", strcat(str1,str2));}

strcpy strncpy

#include<stdio.h>int main(){    char str1[10] = "asdas";    char str2[] = {"China"};    strcpy(str1,str2);    printf("%s",str1);}

strcmp

int main(){    char str1[] = {"compare"};    char str2[] = {"computer"};    if(strcmp(str1,str2)>0)        printf("yes");    else        printf("no");}

strlen

#include<stdio.h>int main(){    char a[10] = {"China"};    printf("%d",strlen(a));}

strlwr

#include<stdio.h>int main(){    char str1[] = {"CHINA"};    printf("%s",strlwr(str1));}

strupr

#include<stdio.h>int main(){    char str1[] = {"china"};    printf("%s", strupr(str1));}

将一个数组中的值按逆序重新存放

#include<stdio.h>int main(){    int a[5];    int i, j, t;    for(i = 0;i < 5;i++)       scanf("%d", &a[i]);    for(j = 0;j < 2;j++)    {        t = a[j];        a[j] = a[4 - j];        a[4 - j] = t;    }    for(i = 0;i < 5;i++)        printf("%d ", a[i]);}