用于将单词转换为大写或小写的函数将整个单词转换为大写或小写。我想要做的是将字符串中特定数量的字符转换为大写或小写。以单词串为例。如果用户只想将单词字符串中的字母S转换为大写,则输出应为:String。此外,此函数还会考虑他们想要转换的单词是否已经是大写或小写。
示例:用户输入单词STRING。想把这个词转换成STRing。 输出:STRING
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
//Function Prototype
int CountVowels(string, int &);
void ShowMenu(string &, char &);
void convertword(string &);
int main()
{
//Variables
string word;
char choice = '0';
int vowels = 0;
do
{
//Call Functions
ShowMenu(word, choice);
switch(choice)
{
case '1':
cout << CountVowels(word, vowels);
cout << endl << endl;
break;
case '2':
convertword(word);
cout << endl << endl;
break;
}
}while(choice != '5');
return 0;
}
void ShowMenu(string& word, char& choice)
{
cout <<"\t\tMENU\t\t" << endl
<<"===========================================" << endl;
cout <<"1. Find the number of Vowels in a word" << endl
<<"2. Convert to uppercase or lowercase " << endl
<<"3. Count the number of uppercase letters " << endl
<<"4. Count the number of lowercase letters" << endl
<<"5. Quit"
<<"\n===========================================" << endl;
//Get menu choice and get word from user.
cout << endl;
cout <<"Enter a choice: ";
cin >> choice;
while((!isdigit(choice)) || (choice > '5'))
{
cerr << "\nOut of range or invalid input. ";
cin >> choice;
}
cin.ignore();
cout << endl;
cout << "Enter a word: ";
getline(cin, word, '\n');
}
int CountVowels(string word, int& vowelCount)
{
vowelCount = 0;
int numLetters = word.length(); //get the number of letters in a word
for (int i = 0; i < numLetters; i++)
{
char letter = word[i]; //get the ith letter in the word
if (letter == 'a' || letter == 'e' ||
letter == 'i' || letter == 'o' ||
letter == 'u' || letter == 'y' )
{
vowelCount++;
}
}
cout << "\nThe number of vowels in this word is : ";
return vowelCount;
}
void convertword(string &word)
{
bool same = false;
char response;
cout << "\nWould you like to convert this word to uppercase or lowercase. " << endl;
cout << "\nType U for uppercase and l for lowercase. ";
cin >> response;
while(response != 'U' && response != 'l')
{
cerr << "\nInvalid input. ";
cin >> response;
}
for(unsigned int i=0; i<word.length(); i++)
{
if((response == 'U' && word[i]==toupper(word[i])))
{
same = true;
}
else if(response == 'U')
{
word[i]=toupper(word[i]);
}
else if((response == 'l' && word[i]==tolower(word[i])))
{
same = true;
}
else if(response == 'l')
{
word[i]=tolower(word[i]);
}
}
cout << endl;
if(same)
{
cout << "\nBased on your response, this word has already been converted. ";
}
else
cout << "\nyour newly converted or unconverted word is : " << word;
cout << endl;
}
答案 0 :(得分:0)
// Capitalizes the first letter and all others are lower case.
size_t n = the number of characters you want.
if( !word.empty() )
{
if( n > word.size() )
n = word.size();
for( size_t i = 0; i < word.size(); ++i )
word[i] = toupper( word[i] );
for( size_t i = n; i < word.size(); ++i )
word[i] = tolower( word[i] );
}