我对C ++中的字符串有疑问。假设我有一个unicode字符串,如下所示:
std::wstring S = L"NAME: STUPID";
上面的字符串可以像
L"AGE: STUPID"
,L"BEHAVIOR: STUPID"
,L"BEHAVIOR: STUPID; NAME: ANONYMOUS"
我想从上面的字符串中提取单词
STUPID
。复制应从给定单词的长度(例如NAME
或BEHAVIOR
的长度)开始,并在找到的第一个分号(;
)处停止。复制应从主字符串完成。 (例如L"NAME: STUPID"
)。我尝试过的
LPCWSTR ExtractSubStringFromString(LPCWSTR & Type, LPCWSTR & String) {
std::wstring S = std::wstring(String);
if (S.find(L";") != std::wstring::npos) // MAIN STRING CONTAINS A SEMICOLON
{
std::wstring S = std::wstring(String + std::wstring(Type).length(), // << CANNOT THINK HOW TO COPY SUBSTRING HERE.
}
else { NO SEMICOLON, ONLY CAN BE A ONE WORD }
}
最佳答案
我认为您正在寻找substr
的std::wstring
方法。这是您要实现的目标的一个可行示例:
std::wstring ExtractSubStringFromString(const std::wstring String)
{
std::wstring S = std::wstring(String);
size_t semicolon = S.find(L';');
// semicolon found?
if (semicolon != std::wstring::npos)
{
// find colon between string start and semicolon
size_t colon = S.find(L':', 0);
if (colon != std::wstring::npos && colon < semicolon)
{
// take string after colon to the semicolon
return S.substr(colon + 1, semicolon - colon - 1);
}
// invalid input parameter
return L"";
}
size_t colon = S.find(L':');
if (colon != std::wstring::npos)
{
size_t count = std::wstring::npos;
if (S[S.length() - 1] == L']')
count = S.length() - 1 - colon - 1;
// return substring after colon to the end
return S.substr(colon + 1, count);
}
// invalid input parameter
return L"";
}
对于输入
STUPID
,<anything>: STUPID
或[<anything>: STUPID]
返回<anything>: STUPID; <anything>: <anything>...
您可能需要照顾空白。