c語言中字符串函數(shù)(庫函數(shù)使用)和模擬實現(xiàn)圖文教程
前言
在寫c語言基礎(chǔ)系列文章時,介紹了字符串函數(shù)strlen(),strcpy(),strcmp()的使用和模擬實現(xiàn)。
本篇文章繼續(xù)探討其他字符串函數(shù)的使用以及模擬實現(xiàn)。
一、庫函數(shù)strcat()介紹
1.1 strcat()介紹
庫函數(shù)strcat()實現(xiàn)的是字符串追加。下面是cplusplus網(wǎng)站關(guān)于這個庫函數(shù)的介紹以及使用。
作用:字符串追加在destination指向的字符串末尾追加source指向的字符串內(nèi)容。注意:
- 源字符串串必須以’\0’結(jié)束
- 目標空間必須足夠大,可以容納源字符串的內(nèi)容
- 目標空間可修改
strcat()的使用
1.2 模擬實現(xiàn)strcat()
參數(shù)1: char* destination
參數(shù)2:const char* source
返回值類型: char*
實現(xiàn)思路:找到destination指向的字符串的末尾位置,即\0位置
把source指向的字符串逐一拷貝到目標字符串中,包含源字符串的\0
代碼實現(xiàn)如下:
#include<assert.h> #include <stdio.h> #include <string.h> char* my_strcat(char* destination, const char* source) { //空指針判斷 assert(destination && source); //保存destinaiton的起始位置 char* dest_start = destination; //1. 找到目標字符串的末尾位置,即\0位置 while (*destination != '\0') { destination++; } //拷貝 while (*destination++ = *source++) { NULL; } return dest_start; }
代碼測試
總結(jié)
到此這篇關(guān)于c語言中字符串函數(shù)(庫函數(shù)使用)和模擬實現(xiàn)的文章就介紹到這了,更多相關(guān)c語言字符串函數(shù)和模擬實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!