C语言中的字符和字符串
生活随笔
收集整理的這篇文章主要介紹了
C语言中的字符和字符串
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C語言在中常常出現(xiàn)字符和字符串,而一串字符或者字符串其實就是數(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");輸出結果:
字符串也有自己特定的輸入和輸出函數(shù)
// gets和puts 字符串的輸入和輸出char ch[100];gets(ch);puts(ch);?
字符串的相關庫函數(shù)部分:需要導入頭文件
#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)) ;結果:
?
?字符函數(shù)部分:需要導入頭文件
#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));//轉變?yōu)榇髮?/span>printf("%C\n",tolower(ch1));//轉變?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");字符串轉為整型或浮點型
需要導入頭文件
#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);數(shù)字轉字符串
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);?
轉載于:https://www.cnblogs.com/qianLL/p/5088608.html
總結
以上是生活随笔為你收集整理的C语言中的字符和字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python数据库访问公共组件及模拟Ht
- 下一篇: 教程 打造OS X Mavericks原