-
Notifications
You must be signed in to change notification settings - Fork 1
/
idxsubstr.cpp
99 lines (82 loc) · 2.33 KB
/
idxsubstr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// {"category": "String", "notes": "Index to first substring in string"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Index to the first character of the first substring in a string.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
int IndexOfSubstring(char* pString, char* pSubstring)
{
if (nullptr == pString || nullptr == pSubstring || '\0' == *pSubstring)
{
return -1;
}
const char* pCopyString = pString;
while (*pString != '\0')
{
char* pStr = pString;
char* pSub = pSubstring;
while (*pStr != '\0' && *pSub != '\0' && *pStr == *pSub)
{
++pStr;
++pSub;
}
if ('\0' == *pSub)
{
return (pString - pCopyString);
}
++pString;
}
return -1;
}
//------------------------------------------------------------------------------
//
// Unit tests
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
struct TestCase
{
char* pString;
char* pSubstring;
int index;
};
const TestCase tests[] =
{
{ "abc", "ab", 0 },
{ "aaa", "bb", -1 },
{ "abc", "abcd", -1 },
{ "abc", "c", 2 },
{ "", "a", -1 },
{ "abc", "", -1 },
{ nullptr, "abc", -1 },
{ "abc", nullptr, -1 },
};
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
int index = IndexOfSubstring(tests[i].pString, tests[i].pSubstring);
bool pass = (index == tests[i].index);
cout << (pass ? "PASS: \"" : "FAIL: \"");
cout << (nullptr == tests[i].pSubstring ? "(null)" : tests[i].pSubstring);
cout << "\" is ";
if (-1 == index)
cout << "not";
else
cout << "at " << index;
cout << " in \"";
cout << (nullptr == tests[i].pString ? "(null)" : tests[i].pString);
cout << "\"" << endl;
}
return 0;
}