Linux C 程式 (12)

來源:互聯網
上載者:User

標籤:

字串函數
C語言的字串處理函數
1.puts函數

1 //把一個以‘\0‘結尾的字串輸出到螢幕2 char a[] = "Welcome to";3 char *p = "Linux C Program";4 puts(a);5 puts(p);

2.gets函數

1 //從終端輸入一個字元數組,返回字元數組的首地址2 char string[20];3 gets(string);4 puts(string);5 //warning: the `gets‘ function is dangerous and should not be used.6 //系統不推薦使用gets方法了,危險

3.strcpy和strncpy

1 #include<string.h>2 char *strcpy(char *dest , char *src);3 char *strncpy(char *dest , char *src ,int n);//複製前n個字元4 //strcpy是string copy縮寫,使用這兩個函數必須包含string.h,傳回值都是dest5 //複製時連同‘\0‘一起被複製

複製錯誤碼示範:

1 char a[] = "Linux C Program " , b[20];2 b = a ;3 //字串複製只能使用strcpy等類似功能的函數

strcpy不安全,容易被駭客利用,一般用strncpy
範例程式碼:

1 char *s = "hello worlg";2 char d1[20],d2[20];3 strcpy(d1,s);4 strncpy(d2,s,sizeof(s));5 //6 //strncpy複製不完全。。。

4.strcat 和strncat

1 #include<string.h>2 char *strcat(char *dest , char *src);3 char *strncat(char *dest , char *src ,int n);//複製前n個字元4 //把輸入的src追加到dest的尾部5 //strcat不安全

5.strcmp    和 strncmp

1 #include<string.h>2 char *strcmp(char *s1 , char *s2);//比較兩個字串3 char *strncmp(char *s1 , char *s2 ,int n);//比較前n字串4 //第一次出現不同字元時,s1-s2的差值為傳回值

6.strlen

 1 #include<string.h> 2 //返回字串的實際長度,不會包括結束符‘\0‘,sizeof(s)的計算會包含結束符 

7.strlwr 和 strupr//string lower 和string upper的縮寫

8.strstr 和 strchr

 1 #include<string.h> 2 char *strstr(char *s1 , char *s2);//s1中尋找s2,返回首次出現指向s2位置的指標,沒有找到返回NULL 3 char *strchr(char *s1 , char c);//s1尋找c首次出現的位置,返回指標,沒有返回NULL 4 //---- 5 #include<stdio.h> 6 #include<string.h> 7  8 int main(){ 9         char *s1 = "Liunx C Program",*s2="unx",*p;10 11         p = strstr(s1,s2);12         if(p != NULL){13                 printf("%s\n",p);14         }else{15                 printf("not found !");16         }17 18         p= strchr(s1,‘C‘);19         if(p != NULL){20                 printf("%s\n",p);21         }else{22                 printf("not found!");23         }24         return 0;25 }

 

Linux C 程式 (12)

相關文章

聯繫我們

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