C++ function string?
make use of int vowelcount(string str) please tell me how to modify this code. i am using character string but the question demands string as a argument
#include<iostream>
#include<cstring>
using namespace std;
int vowelcount ( char *);
int consonantcount ( char *);
int lowercount ( char *);
int uppercount ( char *);
int main(){
char word[80];
cout << "enter a line:";
cin.getline (word, 80);
cout<<" "<<endl;
cout << "vowel count: " << vowelcount(word) << endl;
cout<<"Consonant count :"<<consonantcount(word)<<endl;
cout<<"lowercase letters count :"<<lowercount(word)<<endl;
cout<<"uppercase letters count :"<<uppercount(word)<<endl;
return 0;
}
int vowelcount ( char * pCh){
int vowels = 0;
while(*pCh){
if(strspn(pCh, "aeiouAEIOU"))
vowels++;
pCh++;
}
return vowels;
}
int consonantcount ( char * pCh){
int consonants = 0;
while(*pCh){
if(strspn(pCh, "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"))
consonants++;
pCh++;
}
return consonants;
回答 (2)
If you're going to use C++, let count_if and string::find do the work of iterating through the strings. Here's an example that should give you some ideas for how to write your program:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
typedef enum {
. . Vowel, Consonant, LowerCase, UpperCase, NumCharTypes
} CHAR_TYPE;
bool isVowel(char);
bool isConsonant(char);
bool isLower(char ch) { return islower(ch); }
bool isUpper(char ch) { return isupper(ch); }
typedef bool (*charChecker)(char);
size_t charCount(const string&, charChecker);
charChecker func[] = { isVowel, isConsonant, isLower, isUpper };
string charType[] = {
. . "vowels = ", "consonants = ", "lowercase = ", "uppercase = "
};
int main(int argc, char *argv[]) {
. . string in;
. . while (true) {
. . . . cout << "\nEnter a line: ";
. . . . getline(cin, in);
. . . . cout << "Counts:\n";
. . . . for (size_t i = 0; i < NumCharTypes; i++) {
. . . . . . cout << ". " << charType[i] << charCount(in, func[i]) << "\n";
. . . . }
. . }
. . return 0;
}
bool isVowel(char ch) {
. . static const string vowels("aeiou");
. . return vowels.find(ch) != string::npos;
}
bool isConsonant(char ch) {
. . return isalpha(ch) && !isVowel(ch);
}
size_t charCount(const string &s, charChecker f) {
. . return count_if(s.begin(), s.end(), f);
}
#if 0
Sample run:
Enter a line: Hello, World! 123
Counts:
. vowels = 3
. consonants = 7
. lowercase = 8
. uppercase = 2
#endif
here is one way...
int vowelcount ( string s){
int vowels = 0;
char t;
for(int l=s.length()-1;l>=0;l--){
t=toupper(s[l]);
vowels+=(t =='A' || t=='E' || t=='I' || t=='O' || t=='U') ;
}
return vowels;
}
收錄日期: 2021-04-21 18:22:42
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20160430022704AABSLyC
檢視 Wayback Machine 備份