C語言中的字串函式有如下這些
- 獲取字串長度
- strlen
- 長度不受限制的字串函式
- strcpy
- strcat
- strcmp
- 長度受限制的字串函式
- strncpy
- strncat
- strncmp
- 字串查找
- strstr
- strtok
- 錯誤資訊報告
- strerror
接下來看看如何實作它們
獲取字串長度
strlen
我們看看檔案是怎樣說的,如下
strlen檔案
size_t strlen ( const char * str );Get string length
獲取字串長度
Returns the length of the C string str.
回傳C字串str的長度
The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
C字串長度是由'\0'來確定的,也就是說從字串的第一個開始只要遇到'\0'就結束長度計算(不包含'\0')
This should not be confused with the size of the array that holds the string. For example:
不用困惑你創建的陣列的大小,比如這樣
char mystr[100]="test string";defines an array of characters with a size of 100
chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, whilesizeof(mystr)evaluates to100,strlen(mystr)returns11.定義一個大小為100的陣列
mystr,然后mystr就已經被初始化為一個長度為11的字串了,所以呢,sizeof(mystr)會得出100, 而strlen(mystr)會回傳11.
綜上,可以知道
- 字串已經 '\0' 作為結束標志,strlen函式回傳的是在字串中 '\0' 前面出現的字符個數(不包含 '\0' ),
- 該函式只認'\0',引數指向的字串必須要以 '\0' 結束,
- 注意函式的回傳值為size_t,是無符號的
實作
strlen函式的實作有好幾種,
比如
- 計數器的方法
- 遞回
- 指標 - 指標
接下來一一實作,
1. 計數器:使用一個變數來記錄 - count
斷言指標不為空是個好習慣~
int my_strlen(char* str)
{
int count = 0;
assert(str != NULL);
while (*str != '\0') // while (*str)
{
count++;
str++;
}
return count;
}
就一直找'\0',當*str不是'\0'時,就count++,str++,直到遇到'\0'停止,然后回傳count就是長度了,
2. 遞回
斷言指標不為空是個好習慣~
int my_strlen(char* str)
{
assert(str != NULL);
char* p = str;
while(*p == '\0')
{
return 0;
}
return 1 + my_strlen(p + 1);
}
比如傳入的str地址為 1000
那么 1 + my_strlen(p + 1) 中,p + 1,指標偏移后就是1001,以此類推,
1 + 1 + my_strlen(p + 1)
1 + 1 + 1 + my_strlen(p + 1)
1 + 1 + 1 + 1 + my_strlen(p + 1)
...
1 + 1 + 1 + 1 + ... + 0
最終就可以得出長度,
3. 指標-指標
斷言指標不為空是個好習慣~
int my_strlen(char* str)
{
assert(str != NULL);
char* p = str;
while (*p != '\0')
{
p++;
}
return p - str;
}
把指標str的地址賦值給一個新的指標p,str作為指向起始地址的指標,不改變它,記錄起始地址,
然后通過指標p進行查找'\0',判斷當前字符是否為'\0',不是就進行p++,然后繼續判斷下一個字符,如此回圈,直到指標p找到'\0',然后用 當前的指標p 減去 起始指標str 進行回傳,就是長度了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/276932.html
標籤:其他
