使用 std::for_each
和std::count_if
可以方便地分割字符串。
在 Node Editor 项目中,需要把类中的字段动态地反射到UI控件上。 在UI控件上,需要显示这个字段的名字(property name)和值(property value)。
image.png
在C++代码中,字段名(property name)不允许出现空格,而UI中,要有空格才能显得美观。所以,我的做法是,在每个大写字母前插入空格,以分割字符串。最后把分割好的字符串显示在UI上。
std::string StringUtils::SplitByCapitalLetter(const std::string& str)
{
/* 先统计当前字符串内有多少大写字母。*/
size_t newLen = std::count_if(str.begin(), str.end(), [](char c) {
return std::isupper(c);
});
/* 存储新字符串的 Buffer */
std::string newStr;
/* 为插入的空格预留出空间,提高效率 */
newStr.reserve(newLen + str.length());
/* 遍历字符串中的所有字符 */
std::for_each(str.cbegin(), str.cend(), [&newStr](char ch) {
/* 如果是大写字母,而且不是第一个出现的 */
if (std::isupper(ch) && newStr.length() != 0)
{
/* 先插入空格 */
newStr.push_back(' ');
}
/* 再插入字符 */
newStr.push_back(ch);
});
return newStr;
}