Design Pattern Examples
Overview of object-oriented design patterns
strstri.cpp
Go to the documentation of this file.
1
8
9#include <ctype.h>
10#include "strstri.h"
11
12namespace Helpers
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
35 char* strstri(
36 const char* s1,
37 const char* s2)
38 {
39 // Guard against null pointers (strstr() does not do this).
40 if (s1 == nullptr || s2 == nullptr)
41 {
42 return (nullptr);
43 }
44
45 // If string to search for is empty, return beginning of str1.
46 if (*s2 == '\0')
47 {
48 return ((char*)s1);
49 }
50
51 // Loop over all characters in string to search
52 while (*s1 != '\0')
53 {
54 // Find first occurrence of second string in string 1
55 while (*s1 != '\0' && toupper(*s1) != toupper(*s2))
56 {
57 s1++;
58 }
59
60 if (*s1 == '\0')
61 {
62 break;
63 }
64 const char* sc1;
65 const char* sc2;
66
67 // Now that the first character of string 2 might have been
68 // found, compare subsequent characters of string 2 to see
69 // if we have an exact match.
70 for (sc1 = s1, sc2 = s2; ; )
71 {
72 if (*++sc2 == '\0')
73 {
74 // We have reached the end of the string to search for
75 // so we must have a match. Return pointer into s1
76 // to the found string.
77 return ((char*)s1);
78 }
79 else
80 {
81 ++sc1;
82
83 if (toupper(*sc1) != toupper(*sc2))
84 {
85 // a character in string 2 doesn't match so start
86 // the whole thing over with the next character
87 // in string 1.
88 break;
89 }
90 }
91 }
92 ++s1;
93 }
94 // If we get here, there is no match so return nullptr.
95 return (nullptr);
96 }
97
98} // end namespace
Declaration of the strstri function, case-insensitive string search for narrow character strings.
The namespace containing all the "helper" functions in the C++ code.
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.cpp:35