1,字串函式
字串中函式的中出現n的地方都是從來限制長度
字串長度獲取:strlen
#include
#include
int main()
{
int i=0; char str[]=“hello”; char str1[]={‘h’,‘e’,‘l’,‘l’,‘o’};
printf(“sizeof(str)=%lu\n”,sizeof(str));
printf(“sizeof(str1)=%lu\n”,sizeof(str1));
printf(“strlen(str)=%lu\n”,strlen(str));
printf(“strlen(str1)=%lu\n”,strlen(str1));
return 0;
}
strnlen - determine the length of a fixed-size string #include
字串的拼接:
strcat:
strcat, strncat - concatenate two strings SYNOPSIS #include
#include
#include
int main()
{
int i=0; char str[15]=“hello”;
char buf[6]=“world”;
printf(“%s\n”,strcat(str,buf));
printf(“%s\n”,strncat(str,buf,2));
return 0;
}
字串的比較:
strcmp, strncmp - compare two strings #include #include #include #include #include int main() { int ret=0; char str[15]=“hellp”; char buf[6]=“hello”; ret=strcmp(str,buf); if(ret>0) { printf(“str>buf\n”); } else if(ret==0) printf(“str=buf\n”); else printf(“str printf(“%d\n”,strncmp(str,buf,4)); return 0; } 字串的複製: strcpy:string copy strcpy, strncpy - copy a string #include #include #include #include int main() { int ret=0; char str[15]=“hello”; char buf[6]=“world”; // printf(“%s\n”,strcpy(str,buf)); printf(“%s\n”,strncpy(str,buf,4)); return 0; } 字串的獲取函式: gets: gets - get a string from standard input (DEPRECATED) #include char *fgets(char *s, int size, FILE *stream); char *s: 是儲存從標準輸入裝置(鍵盤)獲取到字串的首地址,字元陣列的名字 int size: 陣列的大小 FILE *stream:輸入檔案流,我們當前使用的stdin char*:返回首地址 在嵌入式開發中存在三個標準裝置: 裝置流 對應識別符號 對應裝置 標準輸入流: stdin 鍵盤 標準輸出流: stdout 顯示器 標準錯誤流: stderr 顯示器 字串輸出函式: int puts(const char *s); const char *s:待輸出的字串的首地址 int fputs(const char *s, FILE *stream); const char *s:待輸出的字串的首地址 FILE *stream:輸出到的檔案流,我們用stdout #include #include 字元的輸入: getchar: int getchar(void); int:用來接收穫取到的單個字元的ascii碼 int getc(FILE *stream); int:用來接收穫取到的單個字元的ascii碼 FILE *stream:標準輸入流stdin 字元輸出: putchar: int fputc(int c, FILE *stream); int putchar(int c); int c:待輸出的字元 FILE *stream:輸出的目標流,此處是標準輸出流stdout #include #include #include #include int main() { char ch=‘ ’; char buf[20]={0}; //gets(buf);//等同於scanf(“%s”,buf); //puts(buf);//等同於printf(“%s”,buf); fgets(buf,20,stdin); fputs(buf,stdout); //ch=getchar(); //putchar(ch); ch=fgetc(stdin); fputc(ch,stdout); printf(“\n”); return 0; } 提示:帶有f的函式介面針對的輸入輸出流比較多,不帶有f的介面只能對標準輸入輸出操作