使用substr查找附近的字符
Using substr to find nearby characters
所以我试图找到距离我迭代的每个字符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
编译它(以前的版本会抱怨有符号/无符号比较),并且没有强制转换(总是一个好符号)。
更好的版本是start
和end
是word
的迭代器,此时您根本不需要创建子字符串(您可以只查看原始单词中的字符)。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 尝试使用 .substr 将字符串转换为字符
- std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符
- 文本文件中的第一个字符会导致 .substr() 错误
- C 中的特殊字符的子字符串(STD :: substr)
- C++:I用不同的位置调用字符串 substr 两次,转换为常量字符 *,它们返回相同的,为什么
- 使用substr查找附近的字符
- 1中的substr().到最后一个字符C++