C++ 用遞迴方式求字串長度的程式
我們給出了一個字串和一項任務:使用使用者自定義函式或內建函式計算給定字串的長度。
可以採用兩種不同的方式計算字串的長度——
- 使用使用者自定義函式——用這種辦法,我們可以遍歷包含整個字串,直到找到“\o”,並透過遞迴函式呼叫使值不斷遞增 1。
- 使用使用者內建函式——“string.h”標標頭檔案中定義了一個內建函式 strlen,用於計算字串長度。此函式接受單一引數(字串型別),並返回一個整數值作為長度。
示例
Input-: str[] = "tutorials point" Output-: length of string is 15 Explanation-: in the string “tutorials point” there are total 14 characters and 1 space making it a total of length 15.
演算法
Start Step 1-> declare function to find length using recursion int length(char* str) IF (*str == '\0') return 0 End Else return 1 + length(str + 1) End Step 2-> In main() Declare char str[] = "tutorials point" Call length(str) Stop
示例
#include <bits/stdc++.h>
using namespace std;
//recursive function for length
int length(char* str) {
if (*str == '\0')
return 0;
else
return 1 + length(str + 1);
}
int main() {
char str[] = "tutorials point";
cout<<"length of string is : "<<length(str);
return 0;
}輸出
如果我們執行以上程式碼它將生成以下輸出
length of string is : 15
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP