ที่นี่เราจะดู 5 วิธีที่แตกต่างกันในการหาความยาวสตริงใน C++ ใน C++ เราสามารถใช้ character array string แบบดั้งเดิม และ C++ ยังมี String class ด้วย ในบริบทต่างๆ มีเมธอดต่างๆ ในการคำนวณความยาวสตริง
C++ String class มีฟังก์ชัน length() และ size() ใช้ได้เพื่อหาความยาวของ string object สำหรับ C-style strings แบบดั้งเดิม สามารถใช้ฟังก์ชัน strlen() ได้ ซึ่งอยู่ใน header file cstring อีกสองวิธีคือตรงไปตรงมา หนึ่งใช้ while loop อีกหนึ่งใช้ for loop
มาดูตัวอย่างเพื่อเข้าใจแนวคิด
ตัวอย่าง
#include<iostream>
#include<cstring>
using namespace std;
int main() {
string myStr = "This is a sample string";
char myStrChar[] = "This is a sample string";
cout << "String length using string::length() function: " << myStr.length() << endl;
cout << "String length using string::size() function: " << myStr.size() << endl;
cout << "String length using strlen() function for c like string: " << strlen(myStrChar) << endl;
cout << "String length using while loop: ";
char *ch = myStrChar;
int count = 0;
while(*ch != '\0') {
count++;
ch++;
}
cout << count << endl;
cout << "String length using for loop: ";
count = 0;
for(int i = 0; myStrChar[i] != '\0'; i++) {
count++;
}
cout << count;
}
ผลลัพธ์
String length using string::length() function: 23 String length using string::size() function: 23 String length using strlen() function for c like string: 23 String length using while loop: 23 String length using for loop: 23