【问题标题】:How to find letters from a string using an array C++如何使用数组 C++ 从字符串中查找字母
【发布时间】:2017-04-08 15:32:14
【问题描述】:

我正在尝试破译一个句子。对于找到的每个单词,我都想在计数器中添加一个。我有一个嵌套的 for 循环,当用户在句子中键入时,一个 for 循环将循环通过句子(int i = 0),另一个(int j = 0)将循环通过数组,当他们找到对应的字母。我认为我所做的事情是有道理的,但由于某种原因它不起作用。这是我处理本节的代码片段。提前谢谢你:)

#include <iostream>
#include <string>
#include <cctype>

using namespace std;
string alphebet[26] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

string sentence;
cin >> sentence;
for(int i = 0; i < sentence.length(); i++){
    for(int j = 0; j < alphebet; j++){
        if (sentence[i] == alphebet[j]){
            counter_letters = counter_letters + 1;
        }
    }
}

【问题讨论】:

标签: c++ arrays


【解决方案1】:

首先将您的alphebet 更改为像char alphabet[26] 这样的字符数组。然后,您需要使用getline(cin, sentence) 来获取整行输入,例如“Hello World”,而cin &lt;&lt; sentence 只获取第一个单词。接下来,您需要将字符串转换为大写,以便稍后匹配您的alphebet,使用transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper); 执行此操作。之后一定要初始化你的变量counter_letters。作为旁注,您不需要执行counter_letters = counter_letters + 1;,您可以执行counter_letters += 1;counter_letters++;++counter_letters;

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>

using namespace std;
int main() {
    char alphebet[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

    string sentence;
    getline(cin,sentence);
    transform(sentence.begin(), sentence.end(), sentence.begin(), ::toupper);

    int counter_letters = 0;
    for(int i = 0; i < sentence.length(); i++){
        for(int j = 0; j < 26; j++){
            if (sentence[i] == alphebet[j]){
                counter_letters++;
            }
        }
    }
    cout << counter_letters << endl;
}

【讨论】:

  • 嘿,如果我想使用 " sentence = toupper(sentence); " 怎么办……由于某种原因 toupper 不能这样工作。为什么?
  • int toupper ( int c );你用错了,它接受一个字符int c,并以int的形式返回另一个字符。
  • 这就是为什么你必须使用transform
【解决方案2】:

我不确定您的问题,但一个建议是您可能在 input 中输入了空格。 cin 不读取空格,因此您的代码可能无法正常工作

如果这不是问题,请查看下面的链接以计算字符串中的大写、小写字母 How to code a C++ program which counts the number of uppercase letters, lowercase letters and integers in an inputted string?

【讨论】:

  • 应该是评论
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 2021-11-05
  • 1970-01-01
  • 2021-11-19
  • 2012-10-27
  • 1970-01-01
相关资源
最近更新 更多