C中字串知識學習小記,字串知識小記
1:在C中我們說"H"這是一個字串,總共佔有2個位元組,後面有一個'\0'偽零結束符。
'H'這是一個數字。通過下面程式進行驗證。
#include <stdio.h>int main(void){printf("%d %d\n",sizeof("c"),sizeof('s'));}
2:字串建立過程
#include <stdio.h>int main(void){char * p = "hello world!";printf("%s\n", p);}
在這裡,為什麼一個字串可以賦給一個 char * 類型的指標變數呢?
1:當我們寫hello時,就是告訴編譯器,在唯讀資料區段儲存6個位元組。
2:"hello"運算式的值表示字串的第一個字元的地址。
#include <stdio.h>int main(void){char * p = "world";//通過這一段代碼的列印可以看出字串代表的是一個地址。printf("%s\n",p);printf("%c\n",*("hello"));return 0;}
//越界的情況列印出來的資料增長了#include <stdio.h>void func(void){int * p ="hello!";write(1,p,10);}int main(void){int * q = "hello world";func();return 0;}
3:字串中傳遞參數:
#include <stdio.h>int main(void){char * p = "hello word! %d\n";printf(p,5);return 0;}4:修改字串的內容
#include <stdio.h>int main(void){char * p = "hello word!\n"; p[0] = 'H'; //這樣編譯就會出現問題,因為唯讀資料區段的內容不能修改printf("%c\n",p[0]);//printf(p,5);return 0;}
//那麼如果我們想要修改唯讀字串中的內容,我們需要把資料放到一個數組中,相當於複製了一份唯讀資料區段中的內容
例如這樣
#include <stdio.h>#include <string.h>int main(void){ char * p = "hello world!"; char ch[64]; strcpy(ch,p); ch[0]='H'; printf("%s\n",ch); return 0;}
5:求一個字串的有效位元組長:
#include <stdio.h>#include <string.h>int main(void){char * p = "hello";// p[0] = 'H';//printf("%c\n",p[0]);//printf(p,5);char a[] = "hello";//strlen()這個函數是用來求一個字串的有效位元組長度,根據偽零結束時進行判斷printf("%ld\n",strlen(a));return 0;}