![](/img/trans.png)
[英]Why doesn't std::basic_string::substr follow the [begin, end) convention?
[英]substr on std::string doesn't work correctly due to presence of some characters that are invisible, but look like spaces
我有一個std::string
,其中包含我看不到的字符,例如\\xc2
等。
我想要我的字符串的子字符串由於存在諸如''之類的字符而無法正常工作,當我用''中的空格替換它時,該子字符串給出了正確的答案。 盡管此問題已解決,但我不希望任何其他角色將其弄亂。 我如何解決這個問題? [我只想用空格替換所有那些不必要的字符。]
您的文本很可能是UTF-8 Unicode(這是當今最常見的編碼)。 \\ xc2是可能為“無中斷空間”(c2 a0)字符或類似內容的多字節編碼的一部分。 std :: string和substring對字節進行操作,完全不知道您具有unicode,並且不應拆分某些字節對。 您還將獲得不正確的字符數,不正確的大小寫和其他奇怪的效果。
處理此問題的正確方法是使用正確實現unicode的庫。 這意味着將程序中的所有字符串替換為支持unicode的變體。
我知道這需要一些工作,但是另一種選擇是,您今天和明天都要修復此位置,明天您會在其他地方找到另一處發生錯誤的操作。
您可以使用std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t>
將此字符串轉換為std::u16string
。
例:
#include <codecvt>
//Something...
std::string hello = "H€llo World";
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;
std::u16string hello_word_u16 = convert.from_bytes(hello);
std::string hello_world_u8 = convert.to_bytes(hello_word_u16);
使用u16(char16_t),您無需關心雙字節編碼字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.