[英]Only whitespaces in string find_first_not_of() vs find_last_not_of()
我想检查一个wstring是否仅包含空格(准确地说是“ \\ t \\ r \\ n”)。 我使用方法find_last_not_of()
找到了几种解决方案。
关于此方法,我有2个问题:
当我知道在wstring包含非空格字符的情况下,那些字符将在字符串的开头,如果我使用find_first_not_of()
会更好,因为它会尽快返回找到了什么?
两种方法的复杂度都为O(n)还是在这里我错了?
我知道网络上有很多关于这些方法的信息,但是我发现了一些与此主题矛盾的说法。
std::basic_string::find_last_not_of
的实现方式不属于规范的一部分; 因此,我们无法确定是以自然顺序还是反向顺序查找字符。
因此,
让我们看一下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 }
正如人们可能已经猜到的那样,字符串是向后查找的。 在您的特定情况下,应使用std::basic_string::find_first_not_of
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.