这是我必须回答的问题:
Write a program that declares two strings: s1 and s2. Initialize both of them using getline(cin, string) function. a) Output the length of each string b) Output the first appearance of a letter a in the first string c) Output the first appearance of a letter b in the second string d) Output the first word of each string e) Output the last word of each string f) Output first sentence reversed g) Output second sentence with the words reversed ( the last word goes first, second last second, and so on) h) Output the total number of vowels in the first sentence i) Output the total number of consonants in the second sentence
这是我到目前为止所做的:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1,s2,s3;
int blank = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int s2temp = 0;
cout << "enter two sentences" <<endl;
getline (cin, s1);
getline (cin, s2);
s3=s2;
// a
cout << "the length of the first string is " << s1.length() << endl;
cout << "the length of the second string is " << s2.length() << endl;
// b
cout<<"the first appearance of the letter 'A' in the first string is ";
cout << s1.find("a");
cout <<endl;
// c
cout<<"the first appearance of the letter 'B' in the second string is ";
cout << s2.find("b");
cout <<endl;
// d
int s1_first = s1.find(" ");
int s2_first = s2.find(" ");
cout << "the first word in the first string is " << s1.substr(0,s1_first) <<endl;
cout << "the first word in the second string is " << s2.substr(0,s2_first) <<endl;
// e
cout << "the last word in the first string is " << s1.substr(s1.find_last_of(" "), s1.length()-1) <<endl;
cout << "the last word in the second string is " << s2.substr(s2.find_last_of(" "), s2.length()-1) <<endl;
// f
for(int i = s1.length()-1; i >= 0; i--)
cout <<s1.substr (i,1)<<endl;
// g
return 0;
}
我为g
,h
和i
尝试了一些不同的东西,但没有一个有效,所以我想我会寻求帮助。
答案 0 :(得分:-1)
计算元音的一种方法是制作一个包含元音的字符串:
static const std::string vowels = "aeiouAEIOU";
接下来,对于字符串中的每个字符,在元音字符串中搜索它:
unsigned int vowel_count = 0;
const size_t length = text.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = text[i];
if (vowels.find(c) != std::string::npos)
{
++vowel_count;
}
}
这也可以应用于辅音。
可以为不允许使用std::string
的用户修改代码。
另一种方法是使用std::map
。