检测两个字符串之间的重叠长度
int overlap(const char *s1, const char *s2){
int i = 0;
while (s1[i] && s2[i] && s1[i] == s2[i])
i++;
return i;
}
这将返回作为输入的两个字符串之间子字符串重叠的长度。但是,如果两个字符串是:
abcdefg
1234efg
它返回 0 的重叠,因为它只能读取从字符串开头开始的重叠,有人可以修改或帮助我制作它,以便它可以读取重叠,无论它们在哪里琴弦?
int overlap(const char *s1, const char *s2){
int i = 0;
while (s1[i] && s2[i] && s1[i] == s2[i])
i++;
return i;
}
This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:
abcdefg
1234efg
it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
执行此操作的简单方法是为两个字符串构建后缀树(这是使用 麦克雷特)。现在只需查找两个字符串中具有起源的最长公共子字符串。
The easy way to do this is to build a suffix-tree for the two strings(this is done using McCreght ). now just look for the longests common substring with origin in both strings.
我认为代码会是这样的:
i think the codes will be like this:
好吧,我又想了这个问题。
我认为你希望每个字符串中的相同索引处有重叠。
注意每个字符串末尾的字符“\0”。
所以我们可以编写如下代码:
对于“abcdefg”和“1234efg”,它将返回3。
well i have thought this question again.
i think you want an overlap at the same index in each string.
pay attention to the character '\0' in the end of each string.
so we can write the codes as the following:
for "abcdefg" and "1234efg", it will return 3.
对我来说看起来有点像家庭作业,是吗?
一旦发现字符串之间存在差异,
while
子句就会退出。您必须遍历整个字符串,并且如果s1[i] == s2[i]
则对每个索引i
进行计数。Looks a little bit like homework to me, is it?
You'r
while
clause exits as soon as it discovers a difference between the strings. You will have to loop over the entire string, and for each indexi
count it ifs1[i] == s2[i]
.假设您希望每个字符串中的相同索引处重叠,如您的示例所示:
将达到目的,尽管它不是很优雅。它将找到相同偏移处第一个重叠的长度。
因此,对于
abcdefgh90
和1234efg890
它将返回 3。如果您想要匹配字符的总数,请尝试:
Assuming that you want an overlap at the same index in each string, as in your example:
will do the trick, although it's not very elegant. It will find the length of the first overlap at the same offset.
So for
abcdefgh90
and1234efg890
it will return 3.If you want the total number of matching characters then try: