【发布时间】:2014-07-10 22:57:17
【问题描述】:
我正在对 HackerRank 进行挑战,其中涉及查找子字符串在一系列字符串中出现的次数。用户输入他们想要测试的字符串数量,以查看它们是否包含“hackerrank”,不区分大小写。我从这里的另一个流行答案中提取了一种方法来将字符串转换为大写。代码如下:
#include <iostream>
#include <string>
#include <cstdio>
#include <cctype>
std::string upperCase(std::string input) {
for (std::string::iterator it = input.begin(); it != input.end(); ++ it)
*it = toupper(*it);
return input;
}
int main(){
int numofStrings;
std::cin >> numofStrings;
std::string tweetString;
int hackerRankOccurrences = 0;
for (numofStrings; numofStrings>0; numofStrings--) {
std::cin >> tweetString;
bool found = upperCase(tweetString).find("HACKERRANK")!=std::string::npos;
if (found) {
hackerRankOccurrences++;
}
}
std::cout << hackerRankOccurrences << std::endl;
}
据我了解,问题在于这个 upperCase 方法将输入的每个单词都返回到不同的行,例如:
你好,这是一句话
变成:
你好,
这个
是
一个
句子
这会导致 for 循环遍历字符串中的每个单词,递减每个使用的单词的总用户输入 numofStrings。
如何让大写字母返回单个字符串/单行输出?
【问题讨论】:
-
在调用
upperCase()之前,您是否尝试打印出tweetString? -
谷歌
c++ get whole line cin的第一个结果:cplusplus.com/forum/beginner/13866