淺析C++中strlen函數(shù)的使用與模擬實(shí)現(xiàn)strlen的方法
strlen函數(shù)的簡單運(yùn)用與模擬實(shí)現(xiàn) strlen函數(shù)的簡單使用strlen函數(shù)的三種模擬實(shí)現(xiàn)使用臨時(shí)變量的方法使用函數(shù)遞歸的方法使用指針相減的方法
strlen函數(shù)的簡單使用
strlen函數(shù)是用來計(jì)算字符串長度的一個(gè)函數(shù),返回類型是size_t
#include<stdio.h> #include<string.h> int main() { char arr[] = "hello world"; size_t;//返回值是size_t unsigned int int len = strlen(arr); printf("len=%d\n", len); return 0; }
下面就是對(duì)于返回值類型是size_t的一個(gè)很形象的例子
int main() { const char* p1 = "abc"; const char* p2 = "adbcdef"; if (strlen(p1) - strlen(p2) > 0) //因?yàn)榉祷刂凳菬o符號(hào)數(shù),所以沒有負(fù)數(shù) { printf("hehe"); } else { printf("haha"); } return 0; }
strlen函數(shù)的三種模擬實(shí)現(xiàn)
使用臨時(shí)變量的方法
#include<stdio.h> #include<assert.h> //模擬實(shí)現(xiàn)strlen size_t my_strlen(const char* str) { int count = 0;//計(jì)數(shù)器 assert(str != NULL); //斷言不是空指針,如果沒有這步,當(dāng)是空指針的時(shí)候可能會(huì)崩潰 while (*str != '\0') { count++; str++; } return count; } int main() { char arr[] = "hello"; int len = my_strlen(arr); printf("%d\n", len); return 0; }
使用函數(shù)遞歸的方法
#include<stdio.h> #include<assert.h> //不使用臨時(shí)變量 size_t my_strlen(const char* str) { assert(str != NULL); if (*str != '\0') { return 1 + my_strlen(str + 1); } else { return 0; } } int main() { char arr[] = "hello"; int len = my_strlen(arr); printf("%d\n", len); return 0; }
使用指針相減的方法
//指針相減的做法 size_t my_strlen(const char* str) { assert(str != NULL); const char* start = str; //str 不能初始化char類型,所以用const while (*str != '\0') { str++; } return str - start; } int main() { char arr[] = "hello"; int len = my_strlen(arr); printf("%d\n", len); return 0; }
到此這篇關(guān)于strlen函數(shù)的使用與模擬實(shí)現(xiàn)strlen的文章就介紹到這了,更多相關(guān)strlen函數(shù)模擬實(shí)現(xiàn)strlen內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++?Qt開發(fā)之使用QUdpSocket實(shí)現(xiàn)組播通信
Qt?是一個(gè)跨平臺(tái)C++圖形界面開發(fā)庫,利用Qt可以快速開發(fā)跨平臺(tái)窗體應(yīng)用程序,本文將重點(diǎn)介紹如何運(yùn)用QUdpSocket組件實(shí)現(xiàn)基于UDP的組播通信,感興趣的可以了解下2024-03-03C++實(shí)現(xiàn)LeetCode(128.求最長連續(xù)序列)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(128.求最長連續(xù)序列),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07數(shù)據(jù)結(jié)構(gòu)之歸并排序的實(shí)例詳解
這篇文章主要介紹了數(shù)據(jù)結(jié)構(gòu)之歸并排序的實(shí)例詳解的相關(guān)資料,這里對(duì)歸并排序進(jìn)行詳細(xì)介紹,需要的朋友可以參考下2017-08-08C++實(shí)現(xiàn)LeetCode數(shù)組練習(xí)題
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode的幾道數(shù)組練習(xí)題,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08