Home > Article > Backend Development > Checks whether a string can be split into two substrings, each containing an equal number of vowels
Welcome to another in-depth guide to the fascinating topic of problem solving in C. This time, we'll tackle the problem of determining whether a string can be divided into two substrings, each containing the same number of vowels. This problem is an excellent exercise for honing your string manipulation and vowel counting skills.
Given a string, our goal is to determine whether it can be divided into two non-empty substrings such that both substrings have the same number of vowels. The vowels in the English alphabet are 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'.
Our approach is to first count the total number of vowels in the string. If the total number is not even, we immediately know that it is impossible to split the string into two substrings with an equal number of vowels.
If the total count is even, then we iterate over the string and count consecutive vowels encountered. If at any time our running count equals half of the total count, we can split the string at that point into two substrings with the same number of vowels.
This is the C code that solves this problem−
#include<bits/stdc++.h> using namespace std; bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); } bool canBeSplit(string s) { int totalVowels = 0; for (char c : s) { if (isVowel(c)) totalVowels++; } if (totalVowels % 2 != 0) return false; int halfVowels = 0; for (char c : s) { if (isVowel(c)) halfVowels++; if (halfVowels == totalVowels / 2) return true; } return false; } int main() { string s="beautiful"; if (canBeSplit(s)) cout << "Yes, the string can be split into two substrings with equal number of vowels." << endl; else cout << "No, the string cannot be split into two substrings with equal number of vowels." << endl; return 0; }
No, the string cannot be split into two substrings with equal number of vowels.
Let us illustrate this problem and its solution with an example -
Assume the string is "beautiful".
We first count the total number of vowels in "beautiful", which is 5. Since this is not an even number, we immediately know that the string cannot be divided into two substrings with an equal number of vowels.
So the output will be "No, the string cannot be split into two substrings with an equal number of vowels."
With this C guide, we learned how to check whether a string can be divided into two substrings such that each substring contains the same number of vowels. This problem is a useful exercise in string manipulation and character counting in C.
The above is the detailed content of Checks whether a string can be split into two substrings, each containing an equal number of vowels. For more information, please follow other related articles on the PHP Chinese website!