Skip to content

Commit 4f6b98d

Browse files
committed
feat(util.string): 添加IsStartWith()与IsEndWith()函数
1 parent a74d855 commit 4f6b98d

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

modules/util/string.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,22 @@ std::string ToLower(const std::string &origin_str)
273273
return target_str;
274274
}
275275

276+
bool IsStartWith(const std::string &origin_str, const std::string &text)
277+
{
278+
if (origin_str.length() < text.length())
279+
return false;
280+
281+
return origin_str.find(text) == 0;
282+
}
283+
284+
bool IsEndWith(const std::string &origin_str, const std::string &text)
285+
{
286+
if (origin_str.length() < text.length())
287+
return false;
288+
289+
return origin_str.find(text, (origin_str.length() - text.length())) != std::string::npos;
290+
}
291+
276292
}
277293
}
278294
}

modules/util/string.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,22 @@ std::string ToUpper(const std::string &origin_str);
156156
*/
157157
std::string ToLower(const std::string &origin_str);
158158

159+
/**
160+
* \brief 判断字串是否以指定字串开头
161+
*
162+
* \param origin_str 原始字串
163+
* \param text 指定字串
164+
*/
165+
bool IsStartWith(const std::string &origin_str, const std::string &text);
166+
167+
/**
168+
* \brief 判断字串是否以指定字串结束
169+
*
170+
* \param origin_str 原始字串
171+
* \param text 指定字串
172+
*/
173+
bool IsEndWith(const std::string &origin_str, const std::string &text);
174+
159175
}
160176
}
161177
}

modules/util/string_test.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,15 @@ TEST(string, ToLower) {
284284
EXPECT_EQ(ToLower(""), "");
285285
}
286286

287+
TEST(string, IsStartWith) {
288+
EXPECT_TRUE(IsStartWith("abc.123", "abc"));
289+
EXPECT_FALSE(IsStartWith("abc.123", "12"));
290+
EXPECT_FALSE(IsStartWith("abc", "abcd"));
291+
}
292+
293+
TEST(string, IsEndWith) {
294+
EXPECT_TRUE(IsEndWith("abc.123", "123"));
295+
EXPECT_FALSE(IsEndWith("abc.123", "bc"));
296+
EXPECT_FALSE(IsEndWith("abc", "abcd"));
297+
}
298+

0 commit comments

Comments
 (0)