注意!!!要嚴格區分單引號和雙引號!單引號內只能是一個字符,而雙引號是字符數組
#include<stdio.h> #include<string.h> #include<stdlib.h>
int main() { char mystr[]="猴子和我一起來,我和猴子一樣帥"; gets(mystr); system("pause"); return EXIT_SUCCESS; }
puts()-----輸出字符串並換行
gets()-----獲取字符串,可以有空格
scanf-----獲取輸入,由於gets()和scanf()無法獲知數組的大小,只有遇到結束符或換行符才終止,不可以有空格,因此可能導致數組越界,所以要加上宏 #define _CRT_SECURE_NO_WARNINGS
要么添加在代碼的開頭,要么添加在IDE的設置項中,如下
fgets() 三個參數 字符指針變量名 長度 輸入流(std):兩種情況----輸入信息小於等於字符指針長度,會在輸入的末尾加上\n\0,或者,在超過長度時,等待換行符\n(也就是當我們敲擊鍵盤回車鍵的時候)的輸入,把\n替換為\0;由此看出fgets()比gets()安全
#include <stdio.h> #include <stdlib.h> int main() { char cpc[10] = { 0 }; char cj[10] = { 0 }; printf("%p\n",cpc); printf("%p\n", cj); fgets(cpc, sizeof(cpc), stdin); printf("%s\n", cpc); system("pause"); }
scanf("%*d%s")%*d忽略數字,*c忽略字符,如果忽略的是字符串就麻煩了,要寫字符串指針長度個*c(例如有100就寫100個)
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char wenwa[]="cpc"; printf("%-5s",wenwa);
printf("%5s",wenwa);
system("pause");
return EXIT_SUCCESS;
}
strlen()字符串長度
int main() { char wenwa[]="sunshine is lady rock you like a baby"; int mylen = strlen(wenwa); printf("%d\n",mylen); printf("%d\n",sizeof(wenwa)); system("pause"); return EXIT_SUCCESS; }
strcpy(目標地址,源地址)字符串拷貝
char target[]; char src[]; if (strcpy(target,src)!=NULL) { }
strncpy()
int main() { char mywords[]="喜歡陳培昌"; char hiswords[]; strcnpy(hiswords,mywords); hiswords[5]=0; printf(hiswords); return EXIT_SUCCESS; }
strcat()
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char myarr[] ={0}; char myarr2[]={0}; gets(myarr); gets(myarr2); printf(strcat(myarr,myarr2)); system("pause"); return EXIT_SUCCESS; }
strncat()
int main() { char myarr[8] = { 0 }; char myarr2[10]={ 0 }; gets(myarr); gets(myarr2); strncat(myarr, myarr2, sizeof(myarr)-strlen(myarr) - 1); puts(myarr); system("pause"); return EXIT_SUCCESS; }
sprintf()向數組打印字符串
strchr(a,'c')在a中找到‘c’,並返回位置。
char *c = strchr(a,'c')
strstr (a,"345")---查找字符串,找不到,返回NULL strtok() 分割字符串 char *p = strtok(); printf(p)
atoi()
char wenwa[] ="789"; printf(atoi(wenwa)); wenwa是char數組 atoi()把數組轉換為整數,兩者地址不一樣
一種怪異的把字符串轉換為數字的方法
char mynum[] = "456"; (mynum[0]-0x30)*1000; + (mynum[1]-0x30)*100; + (mynum[2]-0x30)*10;
字符串逆置
查找數組中第二大的數字
#include <stdio.h> #include <stdlib.h> int main() { int mynum[]={43,88,56,24,78,12,8}; return EXIT_SUCCESS; }
strlen字符串長度不包括末尾的'/0'
sizeof()返回的是數組一共占據了多少字節的內存空間
sprintf存在緩沖區溢出的問題。
strtok()字符串拆分