字符串的串联
Concatenation of strings
本文关键字:字符串 更新时间:2023-10-16
在向量 c++ 中,我有字符串,例如:ACTT CTTG TTGA TGA GA GAGA GAG,如您所见,它们叠加
ACTT
CTTG
TTGA
TG
GAG
所以在对齐中我们可以看到
ACTTGAG
我想将它们连接起来,如您在上面看到的那样,并放入另一个向量。我试过使用子字符串函数,但它不起作用...
这是一个相当简单的算法来重叠两个字符串:
#include <string>
std::string overlap(std::string first, std::string const & second)
{
std::size_t pos = 0;
for (std::size_t i = 1; i < first.size(); ++i)
{
if (first.compare(first.size() - i, i, second, 0, i) == 0)
{
pos = i;
}
}
first.append(second, pos, second.npos);
return first;
}
用法:
std::string result = overlap("abcde", "defgh");
要重叠整个范围,请使用 std::accumulate
:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> strings = {"abc", "def", "fegh", "ghq"};
std::cout << std::accumulate(strings.begin(), strings.end(), std::string(), overlap) << std::endl;
}
假设您仍然使用与上一个问题相同的代码,您可能需要考虑使用元素中的第一个索引(it[0]
)。您可以将此结果添加到字符串中并打印出来。
用:
std::string space = "";
std::string result = "";
auto end = vec.rend();
for(auto it = vec.rbegin(); it != vec.rend(); ++it ) {
if (it == end - 1) {
result += *it;
}
else {
result += it[0];
}
std::cout << space << *it << std::endl;
space += " ";
}
std::cout << result << std::endl;