Design Pattern Examples
Overview of object-oriented design patterns
strstri.c
Go to the documentation of this file.
1
8
9#include <ctype.h>
10#include <stddef.h>
11
12#include "strstri.h"
13
14
16 //
17 // Function : strstri
18 //
19 // Scope : Public
20 //
21 // Arguments : str1 = pointer to string to search in
22 // str2 = pointer to string to search for
23 //
24 // Returns : Pointer into str1 to first character of found str2 or
25 // nullptr if str2 is not found in str1.
26 //
27 // Description: Find string str2 in string str1, returning pointer to first
28 // occurrence of str2. Returns nullptr if str2 not found in str1.
29 //
30 // Notes : This is functionally identical to the C Library's strstr()
31 // except for the use of toupper().
32 //
34
35char* strstri(const char* s1, const char* s2)
36{
37 // Guard against null pointers (strstr() does not do this).
38 if (s1 == NULL || s2 == NULL)
39 {
40 return (NULL);
41 }
42
43 // If string to search for is empty, return beginning of str1.
44 if (*s2 == '\0')
45 {
46 return ((char*)s1);
47 }
48
49 // Loop over all characters in string to search
50 while (*s1 != '\0')
51 {
52 // Find first occurrence of second string in string 1
53 while (*s1 != '\0' && toupper(*s1) != toupper(*s2))
54 {
55 s1++;
56 }
57
58 if (*s1 == '\0')
59 {
60 break;
61 }
62 const char* sc1;
63 const char* sc2;
64
65 // Now that the first character of string 2 might have been
66 // found, compare subsequent characters of string 2 to see
67 // if we have an exact match.
68 for (sc1 = s1, sc2 = s2; ; )
69 {
70 if (*++sc2 == '\0')
71 {
72 // We have reached the end of the string to search for
73 // so we must have a match. Return pointer into s1
74 // to the found string.
75 return ((char*)s1);
76 }
77 else
78 {
79 ++sc1;
80
81 if (toupper(*sc1) != toupper(*sc2))
82 {
83 // a character in string 2 doesn't match so start
84 // the whole thing over with the next character
85 // in string 1.
86 break;
87 }
88 }
89 }
90 ++s1;
91 }
92 // If we get here, there is no match so return nullptr.
93 return (NULL);
94}
Declaration of the strstri function, case-insensitive string search for narrow character strings.
char * strstri(const char *s1, const char *s2)
Do case-insensitive search for string 2 (s2) in string 1 (s1). Similar to the C library's strstr().
Definition: strstri.c:35