-1

在我的程序中,我有一个文本文件被读入一个标记每个单词的数组。我需要这种方式,以便我可以将单词与二叉树中的单词进行比较。问题是......一些重复的单词的格式不同(一个是大写的,一个是小写的),我需要它们这样才能在我的二叉树中找到它们。

所以我的问题是:如何将整个数组更改为小写?

这是我到目前为止所尝试的:

#include <iostream>
#include "Binary_SearchTree.h"
#include "Node.h"
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

const int SIZE = 100;
string myArray[SIZE];

int main() {

    // first constructor will be used since it is empty
    Binary_SearchTree<string> *tree = new Binary_SearchTree<string>();

    string token, lines;
    ifstream file("hashtags.txt");

    while (getline(file, lines)){
            tree -> insertNode(lines);

    }

    // Convert all strings in myArray to all-lower
    myArray = tolower(myArray);

    // tokenize tweet into an array to search
    ifstream tweet1("exampleTweet.txt");
    if(tweet1.is_open())
    {

    while (getline(tweet1, token)){
            for(int i = 0; i < SIZE; ++i)
            {
            tweet1 >> myArray[i];
            }

    }
    tweet1.close();

}
4

1 回答 1

3

使用 C++11 及更高版本,您可以像这样对字符串数组进行小写:

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

std::string myArray[23];

// ...

for (std::string & s : myArray)
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return std::tolower(c); });

或者:

for (std::string & s : myArray)
    std::for_each(s.begin(), s.end(), [](char & c) {
        c = std::tolower(static_cast<unsigned char>(c)); });

甚至:

for (std::string & s : myArray)
    for (char & c : s)
        c = std::tolower(static_cast<unsigned char>(c));

如果您只有 C++98 支持,请使用以下循环:

for (std::size_t i = 0; i != 23; ++i)
{
    std::string & s = myArray[i];
    for (std::string::iterator it = s.begin(), e = s.end(); it != e; ++it)
    {
        *it = std::tolower(static_cast<unsigned char>(*it));
    }
}

你明白了。

不要忘记将字符转换为unsigned char,因为这是std::tolower预期的。(有关讨论,请参阅此问题。)许多 CI/O 函数用unsigned char-converted-to-表示int,因为通常 anint大到足以表示 an 的所有值unsigned char加上额外的带外信息,char并且unsigned char是往返的可转换两种方式以及布局兼容。

于 2015-04-09T21:11:10.073 回答