超详细C语言的字符串函数讲解
字符串函數(shù)
前言
C語言中對(duì)字符和字符串的處理很是頻繁,但是C語言本身是沒有字符串類型的,字符串通常放在常量字符串中或者字符數(shù)組中。字符串常量 適用于那些對(duì)它不做修改的字符串函數(shù)
接下來本文就是對(duì)于介紹一些常用的字符串函數(shù)進(jìn)行講解
所有字符串相關(guān)的函數(shù)都放在string.h的頭文件中
1. strlen😋
size_t strlen ( const char * str ) ;
字符串是以’\0’結(jié)尾的,那么strlen就是返回\0之前的字符個(gè)數(shù)
size_t是定義的一個(gè)宏,本質(zhì)上是一個(gè) unsigned int 類型
那么我們就有思路來實(shí)現(xiàn)strlen了只要遍歷字符串找’\0’
每找一個(gè)字符count就++
找到\0了那么就返回count
下面我們就來模仿一下如何實(shí)現(xiàn)
2.strcpy🤨
char * strcpy ( char * dest, const char * source );
把源字符串source的字符串拷貝到目的字符串dest中
注意會(huì)把source的’\0’也拷貝到dest中
為了避免溢出,dest要有足夠的空間來接受從source拷貝過來的字符串
代碼實(shí)現(xiàn):
3.strcat😏
char * strcat ( char * destination, const char * source );
文檔原文:
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
追加一個(gè)從源字符串拷貝過來的字符串到目的字符串中,目的字符串中的’\0’
會(huì)被源字符串中的第一個(gè)字符給覆蓋掉,并且’\0’會(huì)包含在新生成的字符串中
比如:
char str1[] = “hello”;
char str2[] = “world”;
使用strcat后, str1就會(huì)變?yōu)?#34;helloworld"
原來str1的’\0’會(huì)被’w’字符給覆蓋掉
代碼實(shí)現(xiàn):
4.strcmp🤗
學(xué)會(huì)閱讀文檔
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
代碼實(shí)現(xiàn):
5.strstr😫
const char * strstr ( const char * str1, const char * str2 );
Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
The matching process does not include the terminating null-characters, but it stops there.
功能是判斷str1中是否包含str2這個(gè)子串
如果包含則返回在str1中的指向第一個(gè)出現(xiàn)str2首字符的指針
注意事項(xiàng):這個(gè)比較過程不會(huì)包括’\0’但它會(huì)在’\0’的地方停止比較
這個(gè)函數(shù)比較復(fù)雜舉個(gè)例子:
char str1[] = “hello world”;
char str2[] = “l(fā)lo”;
判斷str1中是否包含str2
顯然是包含的,那么它就會(huì)返回一個(gè)指向’l’的指針
這里我們引入三個(gè)指針,一個(gè)black指向str1的首元素,一個(gè)point指針指向str2的首元素,一個(gè)red指針用來和point比較
比較的步驟:
代碼實(shí)現(xiàn):
const char* myStrstr(const char* str1,const char* str2){assert(str1 != NULL);assert(str2 != NULL);assert(*str1 != '\0');assert(*str2 != '\0');const char* black = str1;while(*black != '\0'){char* point = str2;char* red = black;if(*point != '\0' && *red != '\0' && *point == *red){red++;point++;// 相等的話就都加1比較下一個(gè)字符}// 上述循環(huán)有三種結(jié)束情況// 1.*point == '\0' 那么就找到了子串直接返回black// 2.*red == '\0' 可以直接返回0,將相當(dāng)與red已經(jīng)到了str1的最后 // 3. *point != *red 不相等就不用比較直接進(jìn)入下次循環(huán)if (*point == '\0') {return black;}black++;}return NULL;// 若是循環(huán)結(jié)束了就是沒有找到直接返回NULL }這節(jié)的內(nèi)容就到這啦友友們,有什么疑問歡迎私信我哦
還有兩個(gè)操作內(nèi)存的函數(shù)是以字節(jié)為單位
memmove memcpy
這個(gè)就下次博客再講吧😏😏😏
總結(jié)
以上是生活随笔為你收集整理的超详细C语言的字符串函数讲解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows经典地雷小游戏(C语言实现
- 下一篇: 剑指offer03.数组中重复的数字