简体   繁体   中英

get vowels from char in C++

#include <iostream>
using namespace std;

char a[20];

int main()
{
    cin >> a;
}

If I write for a="home", I want to take the vowels ("o" and "e") and replace them with capital letters ("O" and "E"). how do I do that?

EDIT: Your answers where very helpful. I did something like this:

    cin >> a;

for (int i = 0; a[i] != '\0' && i <= 20; i++)
{
    if (a[i] == 'a')
        a[i] = 'A';
    if (a[i] == 'e')
        a[i] = 'eE';
    if (a[i] == 'i')
        a[i] = 'iI';
    if (a[i] == 'o')
        a[i] = 'oO';
    if (a[i] == 'u')
        a[i] = 'uU';

}

I wanted to change for exemple "e" into "eE" but it doesn't work...

  1. Write a function which will tell you whether something is a vowel or not. This can be as simple as looping through an array or using std::set .
  2. Iterate through the characters and replace the vowels with the return value of toupper .

As a secondary note, you probably want to use std::string instead of char[] .

Basically, you can do this:

#include <iostream>
using namespace std;
char a[20];

int main(){
    cin >> a;
    for (int i = 0; a[i] != '\0' && i < 20; i++){
        if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i'|| a[i] == 'o'|| a[i] == 'u'){
            a[i] = a[i] + 'A' - 'a';
        }
    }
    cout << a;
}

The program iterates each character in the string, and compares it to all five vowels. If it finds it is a vowel, it turns it into uppercase.

The line

a[i] = a[i] + 'A' - 'a';

may seem hard to understand, but it isn't. Every character is actually an integer in a coding system. In most coding systems, the difference between a letter and its corresponding capital letter is a constant given by ('A' - 'a'). So, by adding ('A' - 'a') to any character, you effectively turn it into uppercase.

   //inside the loop body

   cin >> a;
   while(a[i])
   if(a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i]== 'o' || a[i]=='u')
   {
         a[i]=toupper(a[i]);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM