Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

5 วิธีหาความยาวสตริงใน C++


ลำดับของตัวอักษรหรืออาร์เรย์เชิงเส้นของตัวอักษร เรียกว่า String การประกาศเหมือนกับการกำหนดอาร์เรย์อื่นๆ

ความยาวของอาร์เรย์ คือ จำนวนตัวอักษรใน String มีเมธอดในตัว (in-built) และวิธีอื่นๆ หลายอย่างในการหาความยาวของสตริง ที่นี่ เราพูดถึง 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++ − อยู่ในไลบรารี string ของ 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 loop − วิธีนี้ไม่ต้องการฟังก์ชันใดๆ วนลูปผ่านอาร์เรย์และนับจำนวนองค์ประกอบ ลูปทำงานจนกว่าจะเจอ '\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++ มีเมธอด length() ในไลบรารี string ที่คืนจำนวนตัวอักษรในสตริง

โปรแกรมหาจำนวนตัวอักษรในสตริงด้วยเมธอด 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 loop − คุณสามารถนับจำนวนตัวอักษรในสตริงด้วย while loop ได้เช่นกัน ต้องใช้ตัวนับใน while loop และระบุเงื่อนไขสิ้นสุดเป็น != '\0' สำหรับสตริง

โปรแกรมหาความยาวสตริงด้วย WHILE LOOP

#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