删除 C++ 中字符串中第一个单词之前的空格

Remove spaces before the first word in string in C++

本文关键字:单词之 空格 第一个 C++ 字符串 删除      更新时间:2023-10-16

我知道如何在 C 中删除字符串中第一个单词之前的一个或多个空格,但我不知道C++(如果有示例函数(。

我的字符串是:"Hello",我想得到"Hello"。我该怎么办?

使用 std::string::find_first_not_of(' ') 获取第一个非空格字符的索引,然后从那里获取子字符串

例:

std::string str = " Hello";
auto pos = str.find_first_not_of(' ');
auto Trimmed = str.substr(pos != std::string::npos ? pos : 0);

std::string TrimLeft(const std::string& str){
    auto pos = str.find_first_not_of(' ');
    return str.substr(pos != std::string::npos ? pos : 0);
}