C 語言中的字串

2021-10-03 06:31:26 字數 2678 閱讀 6082

在程式設計中,不止會用到數值和字元,也要用到字串。甚至還可以說,字串在程式設計中還有著比較重要的作用。

c 語言中提供了字串,但是並沒有提供字串型別。但這並不意味著不能夠使用字串。

通常會用 「」 來表示這是乙個字串,實際上用 「」 括起來的部分可以認為是字串常量。

通常情況下,字串長度要比 「」 中間的字元數目多乙個,多出來的那個字元是 「\0」。這個字元被稱為字串結束字元,是系統對 「」 表示的字串自動加設的。可以看下邊的程式:

#include int main()

結果為:

the string is hello world

the length of tht string is 12

the ascii is 72,the letter is h

the ascii is 101,the letter is e

the ascii is 108,the letter is l

the ascii is 108,the letter is l

the ascii is 111,the letter is o

the ascii is 32,the letter is

the ascii is 119,the letter is w

the ascii is 111,the letter is o

the ascii is 114,the letter is r

the ascii is 108,the letter is l

the ascii is 100,the letter is d

the ascii is 0,the letter is

從上邊的結果可以看出:

對於字串常量的儲存,c 語言不像其它普通型別常量將之儲存在**段,而是將字串常量儲存在了資料段中的唯讀資料段。也就是通常所說的常量區。

之前我們說到,利用 printf 函式進行輸出時,「hello world」 實際上相當於乙個指標,該指標指向該字串的首位址。也就是說,c 語言內部將字串常量處理為乙個指向該字串常量首位元組位址的指標。因此我們可以將該字串常量賦值給乙個 char * 的指標。

#include int main()

結果為:

pa = 00404064   "hello world" = 00404064

the string is hello world

從結果可以看出:

字元陣列就是陣列中儲存的是字元值。之前我們說字串常量的值不能更改,但是字元陣列是能夠改變值的。

之前提到過,字串比實際看到的字元數目還要多 1。也就是說如果字元陣列在儲存字串中的顯式字元之外再儲存乙個 「\0」,就變成了字串變數。看下邊的程式:

#include int main()

結果為:

the address is 0060fe9c,the string is hello world

the address is 0060fe90,the string is hello world

the address is 0060fe85,the string is hello worldhello world

the address is 0060fe79,the string is hello world

the address is 0060fe9c,the string is hello world

從上邊的結果可以看出:

printf

可以利用 %s 來輸出字串,但是只有在遇到控制字元 「\0」 才會停止輸出。

puts

函式頭為:

int __cdecl puts(const char *_str);
先不用去管 __cdec1,該函式能夠向螢幕列印 _str 對應的內容,成功返回 >0,失敗返回 -1,並會自動換行。

scanf

gets

可以利用下邊的程式自行測試:

#include int main()

可以看這篇文章。

陣列中的各個元素都是字元指標,就稱該陣列為字元指標陣列,或者是指標陣列。看下邊的程式:

#include int main()

; char *b = ;

for (int i = 0; i < 3; i++)

printf("%s\n",a[i]);

for (int i = 0; i < 3; i++)

printf("%s\n",b[i]);

return 0;

}

結果為:

book

desk

light

book

desk

light

從上邊的結果可以看出:

C語言中的字串

從概念上講,c語言中沒有字串型別 在c語言中使用字元陣列來模擬字串 c語言中的字串是以 0 結束的字元陣列 c語言中的字串可以分配於棧空間,堆空間或者唯讀儲存區 char s1 沒有 0 所以s1只不過是個單純的字元陣列 char s2 也是乙個字元陣列,但是最後乙個元素是 0 因此s2就成了c語言...

c語言中的字串

一 c語言中的字串 c語言中沒有字串型別 字串實際就是多個字元連在一起,所有可以用字元陣列來存放字串。但是使用字元陣列輸出時需要使用for迴圈 例如 這樣使用十分不方便,有沒有一種簡約的方式,讓我們一下子就能輸出呢?有但是需要改兩個地方!1.長度要 1 2.末尾要加乙個 0 然後用 s 格式化控制符...

C語言中的字串

1.標準函式gets與puts分別用於字串的整體輸入和輸出,且gets接收字串時,字串中可包含空格。使用格式為 gets 字元陣列 或者puts 字元陣列 由標頭檔案stdio.h支援 2.常用字串處理函式 由標頭檔案string.h strlen 測試字串長度的函式,函式返回值為字串的實際長度 s...