将String Array更改为tolower

时间:2015-04-09 21:08:55

标签: c++ arrays readfile tolower

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

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

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

#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();

}

1 个答案:

答案 0 :(得分: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 expects。 (有关讨论,请参阅this question。)许多CI / O函数以unsigned char - 转换为 - int表示,因为通常int足够大表示unsigned char的所有值以及其他带外信息,charunsigned char可以双向转换,也可以布局兼容。