สตริงคืออาร์เรย์อักขระหนึ่งมิติที่สิ้นสุดโดยอักขระ null ความยาวของสตริงคือจำนวนอักขระในสตริงก่อนอักขระว่าง
ตัวอย่างเช่น
char str[] = “The sky is blue”; Number of characters in the above string = 15
มีโปรแกรมหาความยาวของสตริงดังนี้
ตัวอย่าง
#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
ในโปรแกรมข้างต้น ตัวแปรการนับจะเพิ่มขึ้นในขณะที่วนซ้ำจนกว่าจะถึงอักขระ null ในสตริง ในที่สุดตัวแปรการนับจะถือความยาวของสตริง ได้ดังนี้
while (str[count] != '\0') count++;
หลังจากได้รับความยาวของสตริงแล้ว จะแสดงบนหน้าจอ สิ่งนี้แสดงให้เห็นโดยข้อมูลโค้ดต่อไปนี้
cout<<"The string is "<<str<<endl; cout<<"The length of the string is "<<count<<endl;
ความยาวของสตริงสามารถพบได้โดยใช้ฟังก์ชัน 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