如何使用C++检查<wstring>是否以某个字符串开头

4
我需要检查wstring是否以特定字符串开头。
const wstring str = "Hello World";
wstring temp="Hello ";

如何检查 str 是否以 temp 开头?


听起来很像https://dev59.com/K3I-5IYBdhLWcg3wZ3YR。 - celavek
1个回答

11

首先使用宽字符字面量,然后就轻而易举了:

std::wstring const str = L"Hello World";

// one method:
if (str.substr(0, 6) == L"Hello ") { /* yay */ }

// another method, better:
if (str.find(L"Hello ") == 0) { /* hooray */ }

如果您不想硬编码temp,请使用str.substr(0,temp.size()) == temp。 - oz10
第二个不应该是 if (str.find(L"Hello ") == 0) { /* hooray */ } 吗?因为 OP 想知道字符串是否以 Hello 开头。 - Praetorian
第二个将找到不在开头的"Hello"子字符串...需要改进。 - celavek
感谢大家的帮助! - JChan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接