ระบุด้วยสตริงและภารกิจคือการคำนวณความยาวของสตริงที่กำหนดโดยใช้ฟังก์ชันที่ผู้ใช้กำหนดหรือฟังก์ชันที่สร้างขึ้น
ความยาวของสตริงสามารถคำนวณได้สองวิธี -
- การใช้ฟังก์ชันที่ผู้ใช้กำหนด − ในการดำเนินการนี้ ให้สำรวจทั้งสตริงจนกว่าจะพบ '\o' และเพิ่มค่าต่อไป 1 ผ่านการเรียกใช้ฟังก์ชันแบบเรียกซ้ำ
- การใช้ฟังก์ชันในตัวของผู้ใช้ − มีฟังก์ชัน in-build strlen() ที่กำหนดไว้ในไฟล์ส่วนหัว "string.h" ซึ่งใช้สำหรับคำนวณความยาวของสตริง ฟังก์ชันนี้รับอาร์กิวเมนต์ประเภทสตริงเดียวและส่งคืนค่าจำนวนเต็มเป็นความยาว
ตัวอย่าง
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