[英]Only whitespaces in string find_first_not_of() vs find_last_not_of()
I want to check if a wstring only contains whitespaces (to be precise: " \\t\\r\\n"). 我想检查一个wstring是否仅包含空格(准确地说是“ \\ t \\ r \\ n”)。 I've found several solutions using the method find_last_not_of()
. 我使用方法find_last_not_of()
找到了几种解决方案。
I've got 2 questions regarding this method: 关于此方法,我有2个问题:
when i know that in the cases where the wstring will contain non-whitespace-characters, those characters will be at the beginning of the string, wouldn't it be better if I'd use find_first_not_of()
since it returns as soon as it found something? 当我知道在wstring包含非空格字符的情况下,那些字符将在字符串的开头,如果我使用find_first_not_of()
会更好,因为它会尽快返回找到了什么?
do both methods have a complexity of O(n) or am i wrong here? 两种方法的复杂度都为O(n)还是在这里我错了?
I know there's a lot of information about these methods in the web, but i've found some contradictory statements on this topic. 我知道网络上有很多关于这些方法的信息,但是我发现了一些与此主题矛盾的说法。
The way std::basic_string::find_last_not_of
is implemented is not part of the specification; std::basic_string::find_last_not_of
的实现方式不属于规范的一部分; thus we can't say if the characters are looked up in natural or reversed order. 因此,我们无法确定是以自然顺序还是反向顺序查找字符。
Hence, 因此,
Let's have a look of the libstdc++'s implementation of std::basic_string::find_last_not_of
(basic_string.tcc): 让我们看一下libstdc ++对std::basic_string::find_last_not_of
(basic_string.tcc)的实现:
1317 template<typename _CharT, typename _Traits, typename _Alloc>
1318 typename basic_string<_CharT, _Traits, _Alloc>::size_type
1319 basic_string<_CharT, _Traits, _Alloc>::
1320 find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const
1321 {
1322 __glibcxx_requires_string_len(__s, __n);
1323 size_type __size = this->size();
1324 if (__size)
1325 {
1326 if (--__size > __pos)
1327 __size = __pos;
1328 do
1329 {
1330 if (!traits_type::find(__s, __n, _M_data()[__size]))
1331 return __size;
1332 }
1333 while (__size--);
1334 }
1335 return npos;
1336 }
As one could have guessed, the string is looked up backward. 正如人们可能已经猜到的那样,字符串是向后查找的。 In your specific case, std::basic_string::find_first_not_of
should be the way to go. 在您的特定情况下,应使用std::basic_string::find_first_not_of
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.