Fix RemoveComments()

dev
Tomasz Kapuściński 2023-08-24 18:45:16 +02:00
parent 53b3062bee
commit 2f80292176
2 changed files with 45 additions and 33 deletions

View File

@ -139,37 +139,29 @@ void StrUtils::Trim(std::string& str)
void StrUtils::RemoveComments(std::string& text)
{
for (size_t i = 0; i < text.size();)
for (size_t i = 0; i < text.size(); i++)
{
// Skip string literal of form "text"
if (size_t start = text.find_first_of('"', i); start != std::string::npos)
char c = text[i];
// If a string literal of form "text" or 'text', skip
if (c == '"' || c == '\'')
{
size_t end = text.find_first_of('"', start + 1);
size_t j = i + 1;
if (end == std::string::npos) break;
while (j < text.size())
{
if (text[j] == c) break;
i = end + 1;
continue;
j++;
}
// Skip string literal of form 'text'
if (size_t start = text.find_first_of('\'', i); start != std::string::npos)
{
size_t end = text.find_first_of('\'', start + 1);
if (end == std::string::npos) break;
i = end + 1;
continue;
i = j;
}
// Find and remove comment of form // comment
if (size_t start = text.find_first_of("//", i); start != std::string::npos)
// If a comment of form // comment, remove and end processing
else if (text[i] == '/' && text[i + 1] == '/')
{
text.erase(std::next(text.begin(), start), text.end());
}
// Nothing else to skip or remove
text.erase(std::next(text.begin(), i), text.end());
break;
}
}
}

View File

@ -60,21 +60,41 @@ TEST(StringUtilTests, RemoveComments)
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "qwerty");
text = "qwerty // comment";
text = R"(qwerty // comment)";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "qwerty ");
EXPECT_EQ(text, R"(qwerty )");
text = "qwerty 'test' // comment";
text = R"(qwerty 'test' // comment)";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "qwerty 'test' ");
EXPECT_EQ(text, R"(qwerty 'test' )");
text = "qwerty \"test\" // comment";
text = R"(qwerty "test" // comment)";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "qwerty \"test\" ");
EXPECT_EQ(text, R"(qwerty "test" )");
text = "qwerty 'test // test'";
text = R"(qwerty 'test // test')";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "qwerty 'test // test'");
EXPECT_EQ(text, R"(qwerty 'test // test')");
text = R"(qwerty "test // test")";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, R"(qwerty "test // test")");
text = R"(// comment "text")";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "");
text = R"(// comment 'text')";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, "");
text = R"("qwerty"//comment)";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, R"("qwerty")");
text = R"('qwerty'//comment)";
StrUtils::RemoveComments(text);
EXPECT_EQ(text, R"('qwerty')");
}
TEST(StringUtilTests, SplitSingle)