【问题标题】:Determining if a substring is contained within a string, case insensitively [duplicate]确定子字符串是否包含在字符串中,不区分大小写[重复]
【发布时间】: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。

如何让大写字母返回单个字符串/单行输出?

【问题讨论】:

标签: c++ string substring


【解决方案1】:

这与upperCase 完全无关,它返回的字符串大小与您传递给它的字符串完全相同。修复,改变:

std::cin >> tweetString;

getline(std::cin, tweetString);

【讨论】:

  • 好吧,我是个假人。谢谢!
猜你喜欢
  • 2016-08-22
  • 1970-01-01
  • 2023-03-12
  • 2021-11-04
  • 2016-03-01
  • 2011-01-17
  • 2014-01-29
  • 1970-01-01
  • 2017-12-13
相关资源
最近更新 更多