[英]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.