使用substr查找附近的字符

Using substr to find nearby characters

本文关键字:字符 substr 查找 使用      更新时间:2023-10-16

所以我试图找到距离我迭代的每个字符X距离内的字符。举个例子。。。。

nearby("abcdefg", 2)

应该返回一个集,每个字符都是一个键,并且其值在2的距离内。它应该是这样的。。。

dictionary('a' -> set(a, b, c), 'b' -> set(a, b, c, d), 'c' -> set(a,b,c,d,e))

我现在的代码是这样的。。。

dictionary<char, set<char>> near(const std::string word, int dist) {
    dictionary<char, set<char>> map;
    for (int x = 0; x < word.size(); x++) {
        for (char letter : word.substr(std::max(0, x - dist), std::min(dist + 1, int(word.size()))))
            map[word[x]].insert(letter);
    }
    return map;
}

问题概述:-然而,它在大多数情况下都有效,因为C++的子字符串,我不能指定索引0到4中的所有字符。相反,它在0处进行索引,然后包括4范围内的任何内容。当我想倒退到前面包含字符4个字母和后面包含字符时,这是有问题的。

到目前为止,我的代码将是正确的,但在末尾保留一个字符。所以看起来是这样的。。。

nearby(abcdefg, 2)
dictionary('c' -> set(a,b,c))

它省略了d.

您只需要:

        const auto start = std::max(0, x-dist);
        const auto end = std::min(x+dist+1, int(word.size());
        const auto len = end - start;
        const auto substring = word.substr(start,len);
        auto &the_set = map[word[x]];
        for (const auto letter : substring)
            the_set.insert(letter);

如注释中所述,如果word.size()>INT_MAX,则会中断。解决方案是在size_t中做所有事情(可以std::string::size_t中做所有的事情,但这太冗长了,实际上并没有给你带来任何好处)。

dictionary<char, set<char>> near(const std::string word, size_t dist) {
    dictionary<char, set<char>> map;
    for (size_t x = 0; x < word.size(); x++) {
        const auto start = (x > dist) ? x-dist : 0;  // Beware underflow
        const auto end = std::min(x+dist+1, word.size());
        const auto len = end - start;
        const auto substring = word.substr(start,len);
        auto &the_set = map[word[x]];
        for (const auto letter : substring)
            the_set.insert(letter);
     }
 }

这个版本的优点是gcc将使用-Werror -Wall编译它(以前的版本会抱怨有符号/无符号比较),并且没有强制转换(总是一个好符号)。

更好的版本是startendword的迭代器,此时您根本不需要创建子字符串(您可以只查看原始单词中的字符)。