สตริงคืออาร์เรย์อักขระหนึ่งมิติที่สิ้นสุดโดยอักขระ null สตริงสามารถมีสระ พยัญชนะ ตัวเลข และช่องว่างได้หลายตัว
ตัวอย่างเช่น
String: There are 7 colours in the rainbow Vowels: 12 Consonants: 15 Digits: 1 White spaces: 6
โปรแกรมหาจำนวนสระ พยัญชนะ ตัวเลข และช่องว่างในสตริงมีดังนี้
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
char str[] = {"Abracadabra 123"};
int vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
for(int i = 0; str[i]!='\0'; ++i) {
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U') {
++vowels;
} else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
++consonants;
} else if(str[i]>='0' && str[i]<='9') {
++digits;
} else if (str[i]==' ') {
++spaces;
}
}
cout << "The string is: " << str << endl;
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;
return 0;
} ผลลัพธ์
The string is: Abracadabra 123 Vowels: 5 Consonants: 6 Digits: 3 White spaces: 1
ในโปรแกรมข้างต้น ตัวแปรสระ พยัญชนะ ตัวเลข และช่องว่าง ถูกใช้เพื่อเก็บจำนวนสระ พยัญชนะ ตัวเลข และช่องว่างในสตริง for loop ใช้ตรวจสอบอักขระแต่ละตัวของสตริง ถ้าอักขระนั้นเป็นสระ ตัวแปรสระก็จะเพิ่มขึ้น 1 เหมือนกันสำหรับพยัญชนะ ตัวเลข และช่องว่าง ข้อมูลโค้ดที่แสดงสิ่งนี้มีดังนี้
for(int i = 0; str[i]!='\0'; ++i) {
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U') {
++vowels;
} else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
++consonants;
} else if(str[i]>='0' && str[i]<='9') {
++digits;
} else if (str[i]==' ') {
++spaces;
}
} หลังจากคำนวณการเกิดขึ้นของสระ พยัญชนะ ตัวเลข และช่องว่างในสตริงแล้ว จะแสดงขึ้น ซึ่งแสดงในข้อมูลโค้ดต่อไปนี้
The string is: Abracadabra 123 Vowels: 5 Consonants: 6 Digits: 3 White spaces: 1