C中字串知識學習小記,字串知識小記

來源:互聯網
上載者:User

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;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.