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

โปรแกรม C++ หาความยาวสตริง (String Length)


ความยาวสตริง = จำนวนตัวอักษรก่อน null character (\0)

ตัวอย่าง: "The sky is blue" มี 15 ตัวอักษร

วิธี 1: ใช้ while loop นับเอง

#include <iostream>
using namespace std;

int main() {
    char str[] = "Apple";
    int count = 0;
    while (str[count] != '\0')
        count++;
    cout << "The string is " << str << endl;
    cout << "The length of the string is " << count << endl;
    return 0;
}

ผลลัพธ์

The string is Apple
The length of the string is 5

อธิบาย

while (str[count] != '\0')
    count++;

count++ จนกว่าจะเจอ \0 แล้วแสดงผล

วิธี 2: ใช้ strlen() จาก

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    char str[] = "Grapes are green";
    int count = 0;
    cout << "The string is " << str << endl;
    cout << "The length of the string is " << strlen(str);
    return 0;
}

ผลลัพธ์

The string is Grapes are green
The length of the string is 16

strlen() คืนค่าความยาว ไม่นับ \0