【发布时间】:2018-11-16 17:15:25
【问题描述】:
这是我必须回答的问题:
编写一个声明两个字符串的程序:s1 和 s2。 使用 getline(cin, string) 函数初始化它们。 a) 输出每个字符串的长度 b) 输出第一个字符串中第一次出现的字母 a c) 输出第二个字符串中第一次出现的字母 b d) 输出每个字符串的第一个单词 e) 输出每个字符串的最后一个单词 f) 输出第一句反转 g)输出第二个句子,单词颠倒(最后一个单词排在最前面,第二个排在最后,以此类推) h) 输出第一句中元音的总数 i) 输出第二句中辅音的总数这是我目前所拥有的:
#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 尝试了一些不同的方法,但都没有奏效,所以我想我会寻求帮助。
【问题讨论】:
-
"...但我还是听不懂" - 你得到了什么做什么?你忽略了提到这一点。顺便说一句,调试器拯救生命 (tm)。
-
基本上每个任务都可以遍历字符串中的单个字符并相应地处理它们,这就像使用数组一样(如
if(my_string[i] == ' ') ...)。有更复杂的方法来操作字符串,使用搜索引擎阅读一些关于字符串的教程,您应该很容易找到这些方法,但对于您的任务,我所说的就足够了。
标签: c++ string search count string-matching