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

โปรแกรม C ++ เพื่อนับสระในสตริงโดยใช้ตัวชี้?


ในการหาเสียงสระจากสตริง เราต้องวนซ้ำผ่านอักขระแต่ละตัวของสตริง ที่นี่เราต้องใช้พอยน์เตอร์เพื่อเลื่อนผ่านสตริง สำหรับสิ่งนี้เราต้องการสตริงสไตล์ C หากสตริงชี้ด้วย str ดังนั้น *str จะเก็บอักขระตัวแรกไว้ที่จุดเริ่มต้น จากนั้นถ้า str เพิ่มขึ้น *str จะชี้อักขระถัดไปเป็นต้น หากอักขระอยู่ใน [a,e,i,o,u] หรือ [A, E, I, O, U] แสดงว่าเป็นสระ ดังนั้นเราจะเพิ่มจำนวน

อัลกอริทึม

นับสระ(str)

begin
   count := 0
   for each character ch in str, do
      if ch is in [a,e,i,o,u] or [A, E, I, O, U], then
         count := count + 1
      end if
   done
   return count
end

ตัวอย่าง

#include<iostream>
using namespace std;
int countVowels(const char *myStr){
   int count = 0;
   while((*myStr) != '\0'){
      if(*myStr == 'a' || *myStr == 'e' || *myStr == 'i' || *myStr == 'o' || *myStr == 'u' || *myStr == 'A' || *myStr == 'E' || *myStr == 'I' || *myStr == 'O' || *myStr == 'U') {
         count++;
      }
      myStr++;
   }
   return count;
}
main() {
   string myStr;
   cout << "Enter String: ";
   cin >> myStr;
   cout << "Number of Vowels: " << countVowels(myStr.c_str());
}

ผลลัพธ์

Enter String: EDucation
Number of Vowels: 5