Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strnstr.c File Reference
#include <string.h>
Include dependency graph for strnstr.c:

Go to the source code of this file.

Functions

char * strnstr (const char *s, const char *find, size_t slen)
 Finds the first occurrence of find in the initial slen characters of the object pointed to by s. More...
 

Function Documentation

◆ strnstr()

char* strnstr ( const char *  s,
const char *  find,
size_t  slen 
)

Finds the first occurrence of find in the initial slen characters of the object pointed to by s.

Locates the first occurrence of the null-terminated string find in the string s, where not more than slen characters are searched. Characters that appear after a ‘\0’ character are not searched.

The behavior is undefined if either find or s is not a pointer to a null-terminated byte string.

Parameters
spointer to the null-terminated byte string to examine
findpointer to the null-terminated byte string to search for
slenmaxinum number of characters to search for
Returns
If find is an empty string, s is returned; if find occurs nowhere in s, NULL is returned; otherwise a pointer to the first character of the first occurrence of find is returned.

Definition at line 48 of file strnstr.c.

49 {
50  char c;
51 
52  if((c = *find++) != '\0')
53  {
54  size_t len = strlen(find);
55  do
56  {
57  char sc;
58  do
59  {
60  if(slen-- < 1 || (sc = *s++) == '\0')
61  {
62  {
63  return (NULL);
64  }
65  }
66  } while(sc != c);
67  if(len > slen)
68  {
69  {
70  return (NULL);
71  }
72  }
73  } while(strncmp(s, find, len) != 0);
74  s--;
75  }
76  return ((char*)(uintptr_t)s);
77 }
int strncmp(const char *s1, const char *s2, size_t n)
Compares at most n characters of two possibly null-terminated arrays.
Definition: strncmp.c:12
size_t strlen(const char *str)
Returns the length of the given null-terminated byte string.
Definition: strlen.c:77
#define NULL
Definition: stddef.h:15

References NULL, strlen(), and strncmp().