字符串

字符串( character string )是以空字符(/0)結尾的char數組。

字符串常量(string constant),是指位於一對雙引號中的任何字符。雙引號裏德字符加上編譯器自動提供的結束標誌/0字符,作爲

一個字符串被存儲在內存裏。

運行結果:

Hi! I'm Clyde the Computer. I have many talents.
Let me tell you some of them.
What were they? Ah, yes, here's a partial list.
Adding numbers swiftly
Multiplying accurately
Stashing data
Following instructions to the letter
Understanding the C language

 

Enough about me -- what's your name?
Nigel Barntwit
Well, Nigel Barntwit, You must have many talents. Tell me some.
Limit yourself to one line's worth.
If you can't think of anything, fake it.
Fencing,yodeling,malingering,cheese tasting,and sighing.
Let's see if I've got that list:
Fencing,yodeling,malingering,cheese tasting,and sighing.
Thanks for the information, Nigel Barntwit.

 

 

如果想在字符串中使用雙引號,可以在雙引號前加一反斜槓

printf(" /" Run spot,run!/"exclaimed./n");

 

 

字符串數組

      初始化數組可以不用指定數組大小,編譯器能通過查找空字符來確定字符串結束,但是定義數組時必須指定數組大小

const char m2[]="if you can't think of anything,fate it";

 

#define LINELEN 81

char name[LINELEN];

 

 

 

char heart[ ]="I love Tillie!";

char *head="I love Tillie!";

 

for(i=0;i<6;i++)                       for(i=0;i<6;i++)

     putchar(heart[i]);                     putchar(head[i]);

 

for(i=0;i<6;i++)                       for(i=0;i<6;i++)     

    putchar(*(heart+1));                 putchar(*(head+1)); 

但是隻有指針可以使用增量運算符

while(*(head)!='/0')

         putchar(*(head++));

在數組形式中heart是個地址常量,改變heart意味着更改數組存儲的位置,可以使用heart+1標識數組下一個元素。

 

 

const char *mytal={

                                   "Adding numbers swiftly",

                                   "Multiplying accurately",

                                   "Stashing data",

                                   "Following instructions to the letter",

                                   "Understand the C language"

                              }

mytal是一個由5個指向char的指針組成的數組。mytal是一個一維數組,而且數組裏的每一個元素都是一個char類型值的地址。

*mytal[0]=='A'     *mystal[1]=='M'  *mytal[2]=='S'

mytal[0]= "Adding numbers swiftly"

可以把mytal[0]看作表示第一個字符串,並被看作是地址,*mytal[0]表示第一個字符串的第一個字符

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章