C语言中的字符和字符串
生活随笔
收集整理的這篇文章主要介紹了
C语言中的字符和字符串
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C語(yǔ)言在中常常出現(xiàn)字符和字符串,而一串字符或者字符串其實(shí)就是數(shù)組
字符數(shù)組的定義
char arr[]={'h','e','l','l','o','\0'};而定義字符串:
char arr1[]="HELLO";字符的輸入和輸出可以向一維數(shù)組那樣用scanf和printf,而字符也可以用自己特定輸入和輸出函數(shù)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");輸出結(jié)果:
字符串也有自己特定的輸入和輸出函數(shù)
// gets和puts 字符串的輸入和輸出char ch[100];gets(ch);puts(ch);?
字符串的相關(guān)庫(kù)函數(shù)部分:需要導(dǎo)入頭文件
#include <string.h>?
char str1[30]="wfds";char str2[]="zfds";strcpy(str1, str2);//把str2復(fù)制到str1中,str1的長(zhǎng)度要比str2大 puts(str1);puts(str2);strcat(str1,str2);//把str2鏈接到str1中,總長(zhǎng)度空間大于兩個(gè)的空間 puts(str1);puts(str2);printf("len=%lu\n",strlen(str1));//計(jì)算字符串的長(zhǎng)度 printf("len=%lu\n",strlen(str2));//不包括'\0' printf("%d\n",strcmp(str1, str2)) ;結(jié)果:
?
?字符函數(shù)部分:需要導(dǎo)入頭文件
#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));//是否為數(shù)字 printf("%c\n",toupper(ch));//轉(zhuǎn)變?yōu)榇髮?/span>printf("%C\n",tolower(ch1));//轉(zhuǎn)變?yōu)樾?/span>字符串大寫變小寫,小寫變大寫
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");字符串轉(zhuǎn)為整型或浮點(diǎn)型
需要導(dǎo)入頭文件
#include <stdlib.h>?
//字符串轉(zhuǎn)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);數(shù)字轉(zhuǎn)字符串
int num=1000;char chs[100];//將num按照%d的格式存儲(chǔ)到chs中sprintf(chs,"%d",num);printf("chs=%s\n",chs);//將字符串按照指定的格式存儲(chǔ)sprintf(chs, "%10s","asdf");printf("chs=%s",chs);?
轉(zhuǎn)載于:https://www.cnblogs.com/qianLL/p/5088608.html
總結(jié)
以上是生活随笔為你收集整理的C语言中的字符和字符串的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python数据库访问公共组件及模拟Ht
- 下一篇: 教程 打造OS X Mavericks原