c++ string 之 find_first_not_of 源码

一:实现之前先说一所find_first_not_of姊妹函数()

(1)find_first_of(string &str, size_type index = 0):(find_first_of的实现例如以下链接:find_first_of的源码)

      查找在字符串中第一个与str中的某个字符匹配的字符。返回它的位置。搜索从index正向開始,假设没找到就返回string::npos

(2) find_first_not_of(cstring &str, size_type index = 0):

       在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index正向開始

假设没找到就返回string::nops

(3)find_last_of(cstring &str, size_type index = 0) :

     在字符串中查找最后一个与str中的某个字符匹配的字符,返回它的位置。搜索从index逆向開始。假设没找到就返回string::nops

(4)find_last_not_of(cstring &str, size_type index = 0):   

     在字符串中查找最后一个与str中的字符都不匹配的字符,返回它的位置。搜索从index逆向開始。假设没找到就返回string::nops

(5)总计 (3) 和(4) 因为从index的逆向開始查找的,也相当于(1)和 (2)中的查找第一个

二:手动实现find_first_of()函数

 // 在字符串中查找第一个与str中的字符都不匹配的字符。返回它的位置。

//搜索从index開始。假设没找到就返回string::nops O(N^2) int MyString::find_first_not_of(const char *str,size_t index) { if(NULL == str || index >=strLength) return npos; size_t i=0,j=0; size_t tmp_len = strlen(str); for(i=index;i<strLength;i++) { for(;j<tmp_len;j++) { if(p_str[i]==str[j]) break; } if(j==tmp_len) break;// 依据跳出的内层for的条件推断,找到即结束循环 } if(i==strLength) return npos;// 未找到,// 依据跳出的内层for的条件推断。找到即结束循环 return i; } int MyString::find_first_not_of(const MyString& str,size_t index) { if(NULL == str || index >=strLength) return npos; size_t i=0,j=0; for(i=index;i<strLength;i++) { for(;j<str.strLength;j++) { if(p_str[i]==str[j]) break;// 假设相等 本轮i就无效了。进行下一轮 } if(j==str.strLength) break;// 依据跳出的内层for的条件推断。找到即结束循环 } if(i==strLength) return npos;// 未找到,// 依据跳出的内层for的条件推断,找到即结束循环 return i; } int MyString::find_first_not_of(const char ch,size_t index) { if(NULL == ch || index >=strLength) return npos; size_t i=0; for(i=index;i<strLength;i++) { if(p_str[i]!=ch)// 跟上面的稍微不同,找一个不等就能够了 break; } if(i==strLength) return npos;// 未找到,// 依据跳出的内层for的条件推断,找到即结束循环 return i; }



原文地址:https://www.cnblogs.com/wzjhoutai/p/7197369.html