Home >Backend Development >PHP Tutorial >PHP Program to Count Vowels in a String
A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be capitalized. or lowercase.
Vowels are alphabetic characters representing specific pronunciations. There are five vowels in English, including caps and lowercase:
<code>a, e, i, o, u</code>
u, o, i, i, a, o, i. There are a total of 6
vowels.The string "PHP" does not contain any vowels, so the count is 0.
The vowels in the string are a, u, i, i, a
. There are a total of4
vowels.Use direct logic methods to count vowels in strings
<code class="language-php"><?php $string = "Anshu Ayush"; $vowel_count = 0; // 将字符串转换为小写 $string = strtolower($string); // 循环遍历字符串中的每个字符 for ($i = 0; $i < strlen($string); $i++) { if (in_array($string[$i], ['a', 'e', 'i', 'o', 'u'])) { $vowel_count++; } } // 输出 echo "字符串 '$string' 中元音的数量是:$vowel_count"; ?></code>
<code>字符串 'anshu ayush' 中元音的数量是:3</code>
Output
Time complexity: O(n)
Use function to count vowels in strings In this method, we use a function to calculate the number of vowels in a string. We use a function so that we can use it later as needed.
<code>a, e, i, o, u</code>
<code class="language-php"><?php $string = "Anshu Ayush"; $vowel_count = 0; // 将字符串转换为小写 $string = strtolower($string); // 循环遍历字符串中的每个字符 for ($i = 0; $i < strlen($string); $i++) { if (in_array($string[$i], ['a', 'e', 'i', 'o', 'u'])) { $vowel_count++; } } // 输出 echo "字符串 '$string' 中元音的数量是:$vowel_count"; ?></code>
Time complexity: O(n)
Space complexity: O(1)
The above is the detailed content of PHP Program to Count Vowels in a String. For more information, please follow other related articles on the PHP Chinese website!