Created
August 10, 2010 11:24
-
-
Save joshpeterson/517106 to your computer and use it in GitHub Desktop.
This code attempts to find a given string within another string, matching the given string exactly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// #FixMyCode | |
// This code attempts to find a given string within another string, matching the given string exactly. | |
// Can you make it more correct, more elegant, faster, or just plain better? If so, please do! | |
// Fork this Gist and tweet me the result @joshuampeterson. | |
#include <string> | |
#include <iostream> | |
bool IsWordDelimiter(char character) | |
{ | |
return character == ' ' || character == '.' || character == ',' || | |
character == ';' || character == '?' || character == '!' || | |
character == ':' || character == '/' || character == '(' || | |
character == ')' || character == '"'; | |
} | |
bool IsStringToFindInStringToSearchMatchingWholeWord(std::string stringToSearch, | |
std::string stringToFind) | |
{ | |
size_t position = stringToSearch.find(stringToFind); | |
while (position != std::string::npos) | |
{ | |
if ((position == 0 || IsWordDelimiter(stringToSearch[position-1])) && | |
(position + stringToFind.size() == stringToSearch.size() || | |
IsWordDelimiter(stringToSearch[position + stringToFind.size()]))) | |
{ | |
return true; | |
} | |
position = stringToSearch.find(stringToFind, position + 1); | |
} | |
return false; | |
} | |
void Validate(bool expectedOutput, std::string stringToSearch, std::string stringToFind) | |
{ | |
bool actualOutput = IsStringToFindInStringToSearchMatchingWholeWord(stringToSearch, stringToFind); | |
if (expectedOutput == actualOutput) | |
if (actualOutput) | |
std::cout << "Success: \"" << stringToFind << "\" found" << std::endl; | |
else | |
std::cout << "Success: \"" << stringToFind << "\" not found" << std::endl; | |
else | |
if (actualOutput) | |
std::cout << "Error: \"" << stringToFind << "\" not found" << std::endl; | |
else | |
std::cout << "Error: \"" << stringToFind << "\" found" << std::endl; | |
} | |
void main() | |
{ | |
std::string gettysburgAddress = "Four score and seven years ago our fathers brought" | |
" forth on this continent, a new nation, conceived in" | |
" Liberty, and dedicated to the proposition that all" | |
" men are created equal."; | |
std::cout << "String to search: " << gettysburgAddress << std::endl; | |
Validate(true, gettysburgAddress, "fathers"); | |
Validate(false, gettysburgAddress, "father"); | |
Validate(true, gettysburgAddress, "all men are created equal"); | |
Validate(false, gettysburgAddress, "Four score and seven year"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment