C語言筆記 常用函式(一)

2021-10-09 05:54:42 字數 3059 閱讀 7218

1. strcpy() 函式用於對字串進行複製(拷貝)

【標頭檔案】string.h

【原型】

char

*strcpy

(char

* strdestination,

const

char

* strsource)

;

【引數說明】

strdestination:目的字串

strsource:源字串

strcpy() 函式會把 源字串複製到 目的字串(保證目的字串足夠大)

返回值:目的字串,也即 strdestination

【例項】

使用c語言 strcpy() 函式將字串 src 複製到 dest

#include

#include

intmain()

;char src[20]

=;strcpy

(dest, src)

;puts

(dest)

;return0;

}

【執行結果】2. strlen() 函式用來求字串的長度(包含多少個字元)【標頭檔案】string.h

【原型】

size_t strlen

(const

char

* str)

;

【引數說明】

引數 str 表示要求長度的字串

返回值:字串 str 的長度

strlen() 函式從字串的開頭位置依次向後計數,直到遇見『\0』, 然後返回』\0』之前的字元數,最終統計的字串長度不包括『\0』

【例項】

使用c語言 strlen() 函式求使用者輸入的字串的長度

#include

#include

intmain()

; size_t len;

gets

(str)

; len =

strlen

(str)

;printf

("length: %d\n"

, len)

;return0;

}

】執行結果】

3. strcmp() 函式用於對兩個字串進行比較(區分大小寫)

【標頭檔案】string.h

【原型】

char

strcmp

(const

char

* str1,const

char

* str2)

;

【引數說明】

引數 str1 和 str2 是參與比較的兩個字串

strcmp() 會根據 ascii 編碼依次比較 str1 和 str2 的每乙個字元,直到出現不到的字元,或者到達字串末尾(』\0『)

返回值:

如果返回值 < 0,則表示 str1 小於 str2

如果返回值 > 0,則表示 str2 小於 str1

如果返回值 = 0,則表示 str1 等於 str2

【例項】使用c語言 strcmp() 函式比較使用者輸入的兩個字串。

#include

#include

intmain()

;char str2[50]

=;int i =1;

doelseif(

strcmp

(str1, str2)

>0)

elseif(

strcmp

(str1, str2)

<0)

i++;}

while

(i <5)

;return0;

}

【執行結果】

4. abs() 函式用於求整數的絕對值

【標頭檔案】math.h 或者 stdlib.h

【原型】

int

abs(

int n)

【引數說明】

n 表示要求絕對值的數

返回值:引數的絕對值

【例項】使用 abs() 函式求整數絕對值

#include

#include

intmain()

【執行結果】

5. strchr() 函式用於查詢給定字串中某乙個特定字元

【標頭檔案】string.h

【原型】

char

*strchr

(const

char

* str,

int c)

;

【引數說明】

str:被查詢的字串

c:要查詢的字元

strchr() 函式會依次檢索字串 str 中的每乙個字元,直到遇見字元 c,或者到達字串末尾(』\0『)

返回值:返回在字串 str 中第一次出現字元 c 的位置,如果未找到該字元 c 則返回 null

【例項】使用c語言 strchr() 函式在一段字母中查詢 』c『 字元

#include

#include

intmain()

else

return0;

}

【執行結果】

以上就是常用的c語言函式第一篇,後續會繼續記錄常用的函式哦

C語言 常用函式(一)

參考部落格 atof 將字串轉換為雙精度浮點型值 atoi 將字串轉換為整型值 atol 將字串轉換為長整型值 strtod 將字串轉換為雙精度浮點型值,並報告不能被轉換的所有剩餘數字 strtol 將字串轉換為長整值,並報告不能被轉換的所有剩餘數字 strtoul 將字串轉換為無符號長整型值,並報...

C語言常用函式筆記

strcmp 比較字串 sscanf 讀取格式化的字串中的資料 memset 初始化記憶體的 萬能函式 通常為新申請的記憶體進行初始化工作。對一段記憶體空間全部設定為某個字元,一般用在對定義的字串進行初始化為 或 0 snprintf 按照format的格式格式化為字串,然後再將其拷貝至str中。最...

C語言常用函式

字串操作函式 記憶體操作函式 file fopen char filename,char type int fclose file stream 返回非0值關閉成功 開啟方式 說明 r 以 唯讀 方式開啟檔案。只允許讀取,不允許寫入。檔案必須存在,否則開啟失敗。w 以 寫入 方式開啟檔案。如果檔案不...