【问题标题】:How to remove non-alphanumeric from a UnicodeString in C++Builder?如何从 C++Builder 中的 UnicodeString 中删除非字母数字?
【发布时间】:2021-05-25 12:16:30
【问题描述】:

在我正在进行的一个项目中,使用 Embarcadero C++Builder,所有源文件在使用字符串时都使用UnicodeString

我发现这个 sn-p 可以从 std::wstring 中删除字符:

#include <cctype>
#include <algorithm>
#include <string>

//...

std::wstring FileHandler::removePunctuation(std::wstring word) 
{
    word.erase(std::remove_if(word.begin(), word.end(), 
                  [](char ch){ return !::iswalnum(ch); }), word.end());
    return word;
}

但是如何将相同的算法应用于UnicodeString?或者,在实现中是否有类似的功能?

【问题讨论】:

    标签: c++builder unicode-string


    【解决方案1】:

    UnicodeString 具有 begin()end() 迭代器,因此您可以像使用 std::wstring 一样使用 std::remove_if()

    但是,UnicodeString 不像 std::wstring 那样具有基于迭代器的 erase() 方法,但它确实具有基于索引的 Delete() 方法。 std::removee_if() 只是将“已删除”的字符移动到字符串的末尾,因此您可以使用 remove_if() 返回的迭代器来计算要从中删除的起始索引,例如:

    #include <cctype>
    #include <algorithm>
    
    //...
    
    UnicodeString FileHandler::removePunctuation(UnicodeString word) 
    {
        auto iter = std::remove_if(word.begin(), word.end(), 
                      [](WideChar ch){ return !::iswalnum(ch); });
        // Note: UnicodeString indexes start at 1, not 0!!
        word.Delete(std::distance(word.begin(), iter) + 1, MaxInt);
        return word;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-15
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多