Fix String::Trim and add test

This commit is contained in:
Ted John 2017-02-24 21:48:06 +00:00
parent 84d69b797b
commit 3b341de835
3 changed files with 38 additions and 19 deletions

View file

@ -399,36 +399,29 @@ namespace String
codepoint_t codepoint;
const utf8 * ch = s.c_str();
const utf8 * nextCh;
const utf8 * firstNonWhitespace = nullptr;
const utf8 * lastNonWhitespace = nullptr;
const utf8 * startSubstr = nullptr;
const utf8 * endSubstr = nullptr;
while ((codepoint = GetNextCodepoint(ch, &nextCh)) != '\0')
{
bool isWhiteSpace = codepoint <= WCHAR_MAX && iswspace((wchar_t)codepoint);
if (!isWhiteSpace)
{
if (firstNonWhitespace == nullptr)
if (startSubstr == nullptr)
{
firstNonWhitespace = ch;
startSubstr = ch;
}
lastNonWhitespace = ch;
endSubstr = ch;
}
ch = nextCh;
}
if (firstNonWhitespace != nullptr &&
firstNonWhitespace != s.c_str())
{
size_t newStringSize = ch - firstNonWhitespace;
return std::string(firstNonWhitespace, newStringSize);
}
else if (lastNonWhitespace != nullptr)
{
size_t newStringSize = lastNonWhitespace - s.c_str() + 1;
return std::string(s.c_str(), newStringSize);
}
else
if (startSubstr == nullptr)
{
// String is all whitespace
return std::string();
}
size_t stringLength = endSubstr - startSubstr + 1;
return std::string(startSubstr, stringLength);
}
}

27
test/tests/StringTest.cpp Normal file
View file

@ -0,0 +1,27 @@
#include <string>
#include <tuple>
#include <gtest/gtest.h>
#include <openrct2/core/String.hpp>
using TCase = std::tuple<std::string, std::string>;
class StringTest : public testing::TestWithParam<TCase>
{
};
INSTANTIATE_TEST_CASE_P(TrimData, StringTest, testing::Values(
TCase("string", "string"),
TCase(" string", "string"),
TCase("string ", "string"),
TCase(" some string ", "some string"),
TCase(" ", ""),
TCase("", "")
));
TEST_P(StringTest, Trim)
{
auto testCase = GetParam();
std::string input = std::get<0>(testCase);
std::string expected = std::get<1>(testCase);
std::string actual = String::Trim(input);
ASSERT_EQ(expected, actual);
}

View file

@ -45,7 +45,6 @@
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<!-- Files -->
<ItemGroup>
</ItemGroup>
@ -56,7 +55,7 @@
<ClCompile Include="sawyercoding_test.cpp" />
<ClCompile Include="$(GtestDir)\src\gtest-all.cc" />
<ClCompile Include="tests.cpp" />
<ClCompile Include="StringTest.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>