带count参数的string::find_last_of找不到目标字符

问题描述 投票:0回答:1

我的业务是查找大文本范围内最后一次出现的字符,因此我必须指定

off
count
来限制范围。

在本例中,我试图找到 100 个字符内的最后一个空格。预期位置 93 介于

the release

之间
    string s = "Huawei launched its new product - a triple-fold smartphone - on Tuesday, just hours after the release of Apple's artificial intelligence (AI)-boosted iPhone 16, which sparked wide discussion about the";
    size_t p = s.find_last_of(" ", 99, 99);
    cout << p << endl;
    cout << s[p];

但出乎我的意料,

p
99
s[p]
s
,这是
s
中的最后一个
releas
。我不明白为什么。

c++ stl c++20 visual-studio-2022
1个回答
0
投票

或者,您可以使用 string_view 提取子字符串,而不会导致内存复制。

string s = "Huawei launched its new product - a triple-fold smartphone - on Tuesday, just hours after the release of Apple's artificial intelligence (AI)-boosted iPhone 16, which sparked wide discussion about the";

    string_view sv = s;
    size_t p = sv.substr(0, 99).rfind(' ');
    cout << p << endl;
    cout << s[p];

这样您就不必在搜索功能中指定

off
count

© www.soinside.com 2019 - 2024. All rights reserved.