我的业务是查找大文本范围内最后一次出现的字符,因此我必须指定
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
。我不明白为什么。
或者,您可以使用 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
。