【发布时间】:2013-12-13 14:52:14
【问题描述】:
这听起来像一个简单的问题,但 C++ 让它变得困难(至少对我来说):我有一个 wstring,我想将第一个字母作为 wchar_t 对象,然后从字符串中删除这个第一个字母。
这里不适用于非 ASCII 字符:
wchar_t currentLetter = word.at(0);
因为它会返回两个字符(循环中)用于诸如德语变音符号之类的字符。
这里也不行:
wchar_t currentLetter = word.substr(0,1);
error: no viable conversion from 'std::basic_string<wchar_t>' to 'wchar_t'
这也不是:
wchar_t currentLetter = word.substr(0,1).c_str();
error: cannot initialize a variable of type 'wchar_t' with an rvalue of type 'const wchar_t *'
还有其他想法吗?
干杯,
马丁
---- 更新 ----- 这是一些应该演示问题的可执行代码。该程序将遍历所有字母并一一输出:
#include <iostream>
using namespace std;
int main() {
wstring word = L"für";
wcout << word << endl;
wcout << word.at(1) << " " << word[1] << " " << word.substr(1,1) << endl;
wchar_t currentLetter;
bool isLastLetter;
do {
isLastLetter = ( word.length() == 1 );
currentLetter = word.at(0);
wcout << L"Letter: " << currentLetter << endl;
word = word.substr(1, word.length()); // remove first letter
} while (word.length() > 0);
return EXIT_SUCCESS;
}
但是,我得到的实际输出是:
f?r ? ? ? 字母:f 信件: ? 字母:r
源文件采用 UTF8 编码,控制台的编码也设置为 UTF8。
【问题讨论】:
-
第一个版本到底有什么问题?你可以为你的元音变音问题发布代码吗?
-
C++ 字符串函数本身并不支持 Unicode。不要指望他们知道变音符号和字母之间的区别。
-
wstring::substr()返回一个新的wstring,而不是单个字符。