0

这是要求:读取一个字符串并循环它,每当遇到一个新单词时将它插入到 std::list 中。如果 . 字符在左边有一个空格、制表符、换行符或数字,在右边有一个数字,那么它被视为小数点,因此是单词的一部分。否则,它将被视为句号和单词分隔符。

这是我从模板程序运行的结果:

foo.bar -> 2 words (foo, bar)
f5.5f -> 1 word
.4.5.6.5 -> 1 word
d.4.5f -> 3 words (d, 4, 5f)
.5.6..6.... -> 2 words (.5.6, 6)

第一次处理字符串 c++ 对我来说似乎很复杂。我真的坚持实现代码。谁能给我一个提示?谢谢

我只是做了一些临时的想法

bool isDecimal(std::string &word) {
    bool ok = false;
    for (unsigned int i = 0; i < word.size(); i++) {
        if (word[i] == '.') {
            if ((std::isdigit(word[(int)i - 1]) || 
                 std::isspace(word[(int)i -1]) || 
                 (int)(i - 1) == (int)(word.size() - 1)) && std::isdigit(word[i + 1]))
                ok = true;
            else {
                ok = false;
                break;
            }
        }
    }
    return ok;
}
    void checkDecimal(std::string &word) {
    if (!isDecimal(word)) {
        std::string temp = word;
        word.clear();
        for (unsigned int i = 0; i < temp.size(); i++) {
            if (temp[i] != '.')
                word += temp[i];
            else {
                if (std::isalpha(temp[i + 1]) || std::isdigit(temp[i + 1]))
                    word += ' ';
            }
        }
    }
    trimLeft(word);
}
4

2 回答 2

2

我认为您可能是从错误的方向解决问题。如果您将条件颠倒过来,似乎会容易得多。在伪代码骨架中为您提供一些指示:

bool isSeparator(const std::string& string, size_t position)
{
    // Determine whether the character at <position> in <string> is a word separator
}

void tokenizeString(const std::string& string, std::list& wordList)
{
    // for every character in string
        // if(isSeparator(character) || end of string)
            // list.push_back(substring from last separator to this one)
}
于 2012-04-28T18:10:18.147 回答
0

我建议使用 flex 和 bison 和 c++ 实现来实现它

于 2012-04-28T17:33:55.023 回答