1. 程式人生 > >求字串的長度

求字串的長度

C語言中的字串是通過字元陣列的形式來模擬的,字元陣列本質上就是一個普通的陣列,只不過每個元素的資料型別是char,C風格字元會在陣列的最後一個元素中填充成\0作為字串結束的標記,雖然C語言的字串是字元陣列,但也是可以用一個char*指向字元陣列的第一個元素,然後用這個指標來表示字串

(1)建立臨時變數的方式求字串的長度
#include <stdio.h>
#include <stdlib.h>
int Strlen(char* str){
int count = 0; //建立了臨時變數
while (*str != ‘\0’){
++count;
++str;
}
return count;
}
int main(){
printf("%d\n", Strlen(“hello world”));
system(“pause”);
return 0;
}
執行結果為在這裡插入圖片描述

(2)不建立臨時變數的方式求字串的長度(遞迴方式)
#include <stdio.h>
#include <stdlib.h>
int Strlen(char* str){
if (*str == ‘\0’){ //str指向的是一個空字串
return 0;
}
return 1 + Strlen(str + 1); //str指向的是當前字串中的一個元素
} //比如:hello 如果指向的是h 那就是1+“ello"字串
int main(){ //的長度
printf(”%d\n", Strlen(“hello world”));
system(“pause”);
return 0;
}
執行結果為在這裡插入圖片描述