开发者

Is there a function in C to find a substring overlap?

开发者 https://www.devze.com 2023-03-06 14:46 出处:网络
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

开发者_开发知识库char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.


Use strstr. Example from link:

/* strstr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");
  strncpy (pch,"sample",6);
  puts (str);
  return 0;
}

Output:

This is a sample string

Note:

The entire substring will be matched ; note that strstr does not do partial matches.


char *strstr(const char *str1, const char *str2);

The function strstr() finds the occurrence of str2 in the str1 and returns the pointer to occurrence of str2 in str1. If no match found, then a null pointer is returned.


Qualification: This function computed overlaps of the type

string1  
    ng1randomcharacters

In this case, the overlap is 3

// Traverses s1 from left to right and s2 from left to right, looking for overlap
int get_overlap(char *s1, char *s2)
{
   int u2 = strlen(s2)-1;
   int p1 = strlen(s1)-1;
   int p2 = 0;

   while( p1>=0 && p2<=u2 )
   {
      if (s1[p1--] != s2[p2++])
      {
         --p2; // no overlap, so correct for incremented value
         break;
      }
   }

   return(p2);
}


There's no builtin function, but it's pretty simple to write:

size_t overlap(const char *s1, const char *s2)
{
    size_t i = 0;

    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;

    return i;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消