如何使用数组C ++从字符串中查找字母

时间:2017-04-08 15:32:14

标签: c++ arrays

我想破译一句话。对于找到的每个单词,我想在计数器中添加一个单词。我有一个嵌套的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;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

首先将您的alphebet更改为类似char alphabet[26]的字符数组。然后你需要使用getline(cin, sentence)来获得像'Hello World'这样的整行输入,而cin << 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;
}

答案 1 :(得分:-1)

我不确定你的问题,但有一个主张是你可能会在输入中输入空格。 cin不读取空格,因此您的代码可能无法正常工作

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