In: Computer Science
C++ PROGRAM (Pointers and char arrays)
IMPORTANT NOTES:
1. CHAR ARRAY MUST BE USED.
2. YOU MUST USE POINTERS.
3. YOU MUST USE THE SWITCH STATEMENT TO EXECUTE THE PROGRAM.
4. ALL MODIFICATIONS MUST BE DONE IN THE SAME ORIGINAL CHAR ARRAY WITHOUT CREATING A NEW ONE.
Write a C++ program that modifies a null teminated char array as follows:
Consonants are positioned at the beginning of the string and vowels are moved to the end of the string.
Example :
Original string : density
New string : dnstyei
CodeToCopy:
vowel_separation.cpp
#include <iostream> /* for cout , cin objects */
#include <cstring> /* for strcpy() function */
using namespace std;
int main() {
/* taking input from user */
string input;
cout << "Original string: ";
cin >> input;
/* creating a character array using pointers to store the input */
char * original_str = new char[input.size()];
/* storing the input into character array */
strcpy(original_str, input.c_str());
int len = input.size();
/* temporary array to store vowels positions in the array */
bool temp[len];
/* to hold the count of number of vowels */
int num_vowels = 0;
/* traversing character array to mark vowel positions and to count
* number of vowels */
for ( int i = 0; i < len; ++i) {
switch(*(original_str + i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
{
/* mark vowel position */
temp[i] = true;
/* increment the vowel count */
num_vowels++;
}
break;
default:
temp[i] = false;
;
}
}
int index = 0;
/* separates vowels by moving them to the end of the string */
while (num_vowels) {
if (temp[index] == true) {
/* checking the second character in a swap is vowel or not */
if (temp[len-num_vowels] != true) {
/* as it is not vowel, un-mark the position,
so that in next traversal, it will be ignored */
temp[index] = false;
}
else {
/* as it is a vowel, keep the mark of second character's position*/
/* and unmark the position of first character in a swap */
temp[len-num_vowels] = false;
}
/* swapping vowel character to the end character position */
char curr_char = *(original_str + (len-num_vowels));
*(original_str + (len-num_vowels)) = *(original_str + index);
*(original_str + index) = curr_char;
num_vowels--;
}
/* incrementing the index */
index = (index + 1) % len;
}
/* printing the new string */
cout << "New string: " << original_str << endl;
/* freeing the allocated heap memory */
delete original_str;
}
OutputScreenshot: