检测两个字符串之间的重叠长度 [英] Detecting length of overlap between two strings

查看:60
本文介绍了检测两个字符串之间的重叠长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它返回 0 的重叠,因为它只能读取从字符串开头开始的重叠,有人可以修改或帮助我使其能够读取重叠而不是字符串中的任何地方吗?

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?

推荐答案

我又想到了这个问题.我认为您希望在每个字符串中的相同索引处重叠.注意每个字符串末尾的字符\0".

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:

int overlap(const char *s1, const char *s2){
    int i = 0;
    while (*s1 != '\0' && *s2 != '\0') {
        if (*s1++ == *s2++) i++;
    }
    return i;
}

对于abcdefg"和1234efg",它将返回3.

for "abcdefg" and "1234efg", it will return 3.

这篇关于检测两个字符串之间的重叠长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆