gpt4 book ai didi

c++有效地获取具有索引的字符串的子字符串

转载 作者:太空狗 更新时间:2023-10-29 23:49:19 24 4
gpt4 key购买 nike

在我的项目中,我必须从 index=0 开始遍历一个大字符串并获得长度为 k 的子字符串。我已经实现了 string::substr() 并想知道是否还有其他有效的方法。

例如:

std::string S ="ABCDEFGHIJKLMN"

我需要从S的开头获取所有长度为5的子串。就像"ABCDE", "BCDEF", "CDEFG" 等等..

我的实现如下:

    void geekfunc(std::string &str)
{
unsigned int index=0;
for (; index<=(str.size()-K);++index)
{
++myseqmap[str.substr(index,K)];
}
}

该函数已被调用一千万次,欢迎尝试其他方法。

最佳答案

如果你使用的是 C++17,你可以使用 string_view作为您的参数和映射键类型。这样您就不会在每次调用 substr 时都复制字符串内容。只需确保您传递给该函数的字符串在您的 map 仍在使用时未被破坏或修改。

std::map<std::string_view, std::size_t> myseqmap;

void geekfunc(std::string_view str)
{
unsigned int index=0;
for (; index<=(str.size()-K);++index)
{
++myseqmap[str.substr(index,K)];
}
}

关于c++有效地获取具有索引的字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com