-
Notifications
You must be signed in to change notification settings - Fork 1
/
strinspect2.cpp
96 lines (81 loc) · 2.28 KB
/
strinspect2.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
// {"category": "String", "notes": "Check if string is 3 letter words"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Write a function that determines if a string is composed only of 3 letter
// words.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
bool Has3LetterWords(char* pString)
{
if (nullptr == pString)
{
return false;
}
size_t indexWord = 0;
size_t numberOfWords = 0;
for (size_t i = 0; i < strlen(pString) + 1; i++)
{
if (isspace(pString[i]) || '\0' == pString[i])
{
if (i > indexWord)
{
++numberOfWords;
if (i - indexWord != 3)
{
return false;
}
}
indexWord = i + 1;
}
}
return (numberOfWords > 0);
}
//------------------------------------------------------------------------------
//
// Unit tests
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
struct TestCase
{
char* string;
bool expected;
};
const TestCase tests[] =
{
{ "foo bar baz", true },
{ "The tan dog barks", false },
{ nullptr, false },
{ "", false },
{ "1", false },
{ "12", false },
{ "123", true },
{ " foo bar ", true },
{ " ", false },
{ " ", false },
{ "foo\t\nbar\nbaz\r\n", true },
{ "The\ttan\tdog\tbarks\r\n", false },
{ "\t", false },
{ "\r\n", false },
};
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
bool result = Has3LetterWords(tests[i].string);
cout << (result == tests[i].expected ? "PASS " : "FAIL ");
cout << (result ? "(true) : \"" : "(false) : \"");
cout << (tests[i].string ? tests[i].string : "(null)") << "\"" << endl;
}
return 0;
}