字符串 find_first_not_of() 与 find_last_not_of() 中只有空格
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()
因为它一找到东西就 returns?
这两种方法的复杂度都是 O(n) 还是我错了?
我知道网上有很多关于这些方法的信息,但我发现了一些关于这个主题的矛盾陈述。
std::basic_string::find_last_not_of
的实现方式不是规范的一部分;因此我们不能说这些字符是按自然顺序还是颠倒顺序查找的。
因此,
- 依赖于实现
- 依赖于实现
让我们来看看libstdc++'s implementation of 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
应该是正确的选择。
我想检查一个 wstring 是否只包含空格(准确地说:“\t\r\n”)。我找到了几个使用方法 find_last_not_of()
.
我有 2 个关于此方法的问题:
当我知道在 wstring 将包含非空白字符的情况下,这些字符将位于字符串的开头,如果我使用不是更好吗
find_first_not_of()
因为它一找到东西就 returns?这两种方法的复杂度都是 O(n) 还是我错了?
我知道网上有很多关于这些方法的信息,但我发现了一些关于这个主题的矛盾陈述。
std::basic_string::find_last_not_of
的实现方式不是规范的一部分;因此我们不能说这些字符是按自然顺序还是颠倒顺序查找的。
因此,
- 依赖于实现
- 依赖于实现
让我们来看看libstdc++'s implementation of 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
应该是正确的选择。