ECCE @ EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
strnstr.cc
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file strnstr.cc
1 /*
2 
3 This function is modelled after the "strstr" function in
4 string.h. There is no standard function which locates a substring in a
5 string which is not 0-terminated. In all other respects the strnstr
6 function is suuposed to behave as strstr, that is, it returns a
7 pointer to the first occurence of string s2 in string s1, only that we
8 can deal here without not 0-terminated strings and rather tell the
9 length of the strings by the s1len and s2len parameters.
10 
11 On some systems the memmem function does this, but it is not available on
12 all systems.
13 
14 */
15 #include <iostream>
16 #include <cstring>
17 
18 char * strnstr (const char *s1, size_t s1len, const char *s2, size_t s2len)
19 {
20 
21  size_t i;
22  char *c;
23 
24  /* if s2len is 0, we are done */
25  if (s2len <= 0) return (char *) s1;
26 
27  /* if s2len > s1len we will not find the substring here. */
28  if (s2len > s1len ) return 0;
29 
30  char *s2copy = new char[s2len+1];
31  c = s2copy;
32  for (i=0; i<s2len; i++) *c++ = s2[i];
33  *c = 0;
34 
35  c = (char *) s1;
36  for (i=0; i <= s1len - s2len; i++)
37  {
38  if (strncmp(c, s2copy, s2len) == 0)
39  {
40  delete [] s2copy;
41  return c;
42  }
43  c++;
44  }
45  delete [] s2copy;
46  return 0;
47 }
48