ลำดับของอักขระหรืออาร์เรย์เชิงเส้นของอักขระเรียกว่าสตริง การประกาศจะเหมือนกับการกำหนดอาร์เรย์อื่นๆ
ความยาวของอาร์เรย์คือจำนวนอักขระในสตริง มีวิธีการในตัวและวิธีการอื่นๆ มากมายในการค้นหาความยาวของสตริง ในที่นี้ เรากำลังพูดถึง 5 วิธีในการค้นหาความยาวของสตริงใน C++
1) ใช้เมธอด strlen() ของ C − ฟังก์ชันนี้จะคืนค่าจำนวนเต็มของ C สำหรับสิ่งนี้ คุณต้องส่งสตริงในรูปแบบของอาร์เรย์อักขระ
โปรแกรมแสดงตัวอย่างการใช้ strlen() วิธีการ
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char charr[] = "I Love Tutorialspoint";
int length = strlen(charr);
cout << "the length of the character array is " << length;
return 0;
} ผลลัพธ์
the length of the character array is 21
2) การใช้ size() วิธีการของ c++ - รวมอยู่ในไลบรารีสตริงของ C ++ ส่งคืนค่าจำนวนเต็มของจำนวนอักขระในสตริง
โปรแกรมแสดงตัวอย่างการใช้ size() วิธีการ
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "I love tutorialspoint";
int length = str.size();
cout << "the length of the string is " << length;
return 0;
} ผลลัพธ์
The length of the string is 21
3) การใช้ for ลูป − วิธีนี้ไม่ต้องการฟังก์ชันใดๆ มันวนรอบอาร์เรย์และนับจำนวนองค์ประกอบในนั้น วนซ้ำทำงานจนกว่าจะพบ '/0'
โปรแกรมหาความยาวโดยใช้ FOR LOOP
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "I love tutorialspoint";
int i;
for(i=0; str[i]!='\0'; i++){ }
cout << "the length of the string is " << i;
return 0;
} ผลลัพธ์
The length of the string is 21
4) ใช้วิธี length() − ใน C ++ เป็น method length() ในไลบรารีสตริงที่ส่งคืนจำนวนอักขระในสตริง
โปรแกรมหาจำนวนอักขระในสตริงโดยใช้วิธี length()
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "I love tutorialspoint";
int length = str.length();
cout << "the length of the string is " << length;
return 0;
} ผลลัพธ์
The length of the string is 21
5) การหาความยาวของสตริงโดยใช้ลูป while − คุณสามารถนับจำนวนอักขระในสตริงโดยใช้ while loop ได้เช่นกัน ในการนับจำนวนอักขระ คุณต้องใช้ตัวนับในลูป while และระบุเงื่อนไขสิ้นสุดเป็น !='\0' สำหรับสตริง
โปรแกรมหาความยาวของสตริงที่ใช้ในขณะที่วนซ้ำ
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "I love tutorialspoint";
int length = 0;
while(str[length] !='\0' ){
length++;
}
cout<<"The length of the string is "<< length;
return 0;
} ผลลัพธ์
The length of the string is 21