C語言在中常常出現字符和字符串,而一串字符或者字符串其實就是數組
字符數組的定義
char arr[]={'h','e','l','l','o','\0'};
而定義字符串:
char arr1[]="HELLO";
字符的輸入和輸出可以向一維數組那樣用scanf和printf,而字符也可以用自己特定輸入和輸出函數gerchar和putchar,而用getchar和putchar輸入一串字符
char arr[1000];
int i=0,j=0;
char ch;
while ((ch=getchar())!='\n') {
arr[i]=ch;
i++;
}
arr[i]='\0';
while (arr[j]!='\0') {
putchar(arr[j]);
j++;
}
printf("\n");
輸出結果:

字符串也有自己特定的輸入和輸出函數
// gets和puts 字符串的輸入和輸出
char ch[100];
gets(ch);
puts(ch);

字符串的相關庫函數部分:需要導入頭文件
#include <string.h>
char str1[30]="wfds";
char str2[]="zfds";
strcpy(str1, str2);//把str2復制到str1中,str1的長度要比str2大
puts(str1);
puts(str2);
strcat(str1,str2);//把str2鏈接到str1中,總長度空間大於兩個的空間
puts(str1);
puts(str2);
printf("len=%lu\n",strlen(str1));//計算字符串的長度
printf("len=%lu\n",strlen(str2));//不包括'\0'
printf("%d\n",strcmp(str1, str2)) ;
結果:

字符函數部分:需要導入頭文件
#include <ctype.h>
char ch='a',ch1='A';
printf("%d\n",isalpha(ch));//是否為字母
printf("%d\n",isupper(ch));//是否為大寫
printf("%d\n",islower(ch));//是否為小寫
printf("%d\n",isdigit(ch));//是否為數字
printf("%c\n",toupper(ch));//轉變為大寫
printf("%C\n",tolower(ch1));//轉變為小寫

字符串大寫變小寫,小寫變大寫
char ch[100],ch1;
gets(ch);
int i=0;
while (ch[i]!='\0') {
ch1=ch[i];
if (isupper(ch1)==1) {
ch1= tolower(ch1);
}else{
ch1=toupper(ch1);
}
putchar(ch1);
i++;
}
printf("\n");

字符串轉為整型或浮點型
需要導入頭文件
#include <stdlib.h>
//字符串轉
char *chs="11.52";
printf("chs=%s\n",chs);
double d=atof(chs);
int a=atoi(chs);
printf("%f\n",d);
printf("%d\n",a);

數字轉字符串
int num=1000;
char chs[100];
//將num按照%d的格式存儲到chs中
sprintf(chs,"%d",num);
printf("chs=%s\n",chs);
//將字符串按照指定的格式存儲
sprintf(chs, "%10s","asdf");
printf("chs=%s",chs);
