《黑馬程式員》 字串 (C語言)

來源:互聯網
上載者:User

標籤:

字串的基本使用定義方法:

char name[10] ="jack";   此時字串中共包含‘j’,’a‘,‘c‘,‘k‘,‘\0‘

中括弧中的10代表該字串最多存放10個字元

字串的輸出

1.printf("jack");

2.printf(name);              //把數組傳入printf語句輸出會出現警告        

這兩種方法輸出結果相同,但printf語句預設情況下只認字串常量,所以第二種方法在編譯時間會出現警告。

字串的儲存細節:

數組name中共佔用8個位元組,含有三個元素分別為‘i‘,‘t‘,‘\0‘

char name[8] ="it";

char name2[8] = {‘i‘,‘t‘,‘\0‘};

char name3[8] = {‘i‘,‘t‘,0};

三種寫法效果相同

註:因’\0‘的ASCII值為0,故’\0‘與0等價

修改數組內元素的值

name[1] = ‘q‘;      //把數組內第2個元素的值改為q;

\0的作用

\0為字串的結束標誌

#include <stdio.h>  int main(){  char name[] ="it";  char name2[] ={‘o‘,‘k‘};  printf("%s\n",name2);  return 0;}
運行結果:okit

資料記憶體如下所示

strlen函數

作用:用來計算字串的長度,strlen函式宣告在<string.h>檔案中,計算的是字元數並不是字數,計算的字元不包括尾部的"\0"

 

#include <stdio.h>  #include <string.h>int main(){char name[] ="haha";                 //定義一個字串數組int size1 =strlen(name);             //計算字串的長度      不包含"\0"int size2 =sizeof(name);             //計算字串的佔用位元組數,包含"\0"        printf("%d\t%d\n",size1,size2);      //輸出        return 0;}
運行結果:4 5
 代碼練習1:
#include<stdio.h>//字串數組int main(){ //一維數組char  name[] ="haha";char name1[] ="rose";char name2[] ="jim";char name3[] ="jake";//二維數組//第一種方法char name[2][10] = {"jake","rose"};//第二種方法char name[2][10] = {{‘j‘,‘a‘,‘k‘,‘e‘,‘\0‘};{‘r‘,‘o‘,‘s‘,‘e‘,‘\0‘}; };        return 0;}
  代碼練習2:
#include <stdio.h>#include <string.h>/*編寫一個函數char_contains(char str[],char c),如果字串中str中包含字元C,則返回數值1,否則返回數值0.*/int char_contains(char str[],char c){int i;//遍曆數組內所有元素,檢測數組內是否包含字元Cfor(i = 0;i < strlen(str);i++){if(str[i] ==c){//返回數值1return 1;}}return 0;}int main(){   char  str[]="itcast";int result = char_contains(str,‘c‘);printf("%d\n",result);return 0;}

 

《黑馬程式員》 字串 (C語言)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.