3.4 字符串的查找
1. string的find函数族
find
:在一个字符串中,查找一个指定的字符或字符串,返回首次匹配的开始位置
find_first_of
:在一个字符串中,查找一个字符组中任一字符,返回首次匹配的开始位置
find_last_of
:在一个字符串中,查找一个字符组中任一字符,返回最后一个匹配的位置
find_first_not_of
:在一个字符串中,查找与一个字符组中任一字符都不匹配的字符,返回首次不匹配的开始位置
find_last_not_of
:在一个字符串中,查找与一个字符组中任一字符都不匹配的字符,返回最后一次不匹配的位置
rfind
:find从后往前找
2. 反向查找
如果需要在字符串中从后往前查找,可以使用rfind
成员
#pragma once #include <cstddef> #include <string> #include <vector> #include <iostream> using std::size_t ;using std::string;using std::vector;class RparseTest { vector<string> strings; public : void parseForData () { string s ("now;sense;make;to;going;is;This" ) ; int last = s.size (); size_t current = s.rfind (';' ); while (current != string::npos) { ++current; strings.push_back (s.substr (current, last - current)); current -= 2 ; last = current + 1 ; current = s.rfind (';' , current); } strings.push_back (s.substr (0 , last)); } void show () { for (const auto & i : strings) { std::cout << i << std::endl; } } }; int main (int argc, char const * argv[]) { RparseTest t; t.parseForData (); t.show (); return 0 ; }
3. 查找一组字符第一次或最后一次出现的位置
3.1 去除头尾的空字符
#pragma once #include <string> #include <cstddef> inline std::string trim (const std::string& s) { const char *whiteSpace = " \a\b\f\n\r\t\v" ; if (!s.length ()) return s; std::size_t beg = s.find_first_not_of (whiteSpace); std::size_t end = s.find_last_not_of (whiteSpace); if (beg == std::string::npos) return "" ; return std::string (s, beg, end - beg + 1 ); }
4. 从字符串中删除字符
使用erase
成员函数删除字符串中的字符。
参数:
所以,使用无参erase()
删除本字符串的所有字符。
4.1 删除HTML文件中的tag和特殊标记
实现思路:
将特殊标记替换为<和>,或者是空字符
查找<标记,删除直到>标记的所有。
#include <cassert> #include <cstddef> #include <fstream> #include <iostream> #include <string> #include "RepalceAll.h" #include "../require.h" using namespace std;string& stripHTMLTags (string& s) { static bool inTag = false ; bool done = false ; while (!done) { if (inTag) { size_t rightPos = s.find (">" ); if (rightPos != string::npos) { inTag = false ; s.erase (0 , rightPos + 1 ); } else { done = true ; s.erase (); } } else { size_t leftPos = s.find ("<" ); if (leftPos != string::npos) { size_t rightPos = s.find (">" ); if (rightPos == string::npos) { inTag = done = true ; s.erase (leftPos); } else { s.erase (leftPos, rightPos - leftPos + 1 ); } } else { done = true ; } } } replaceAll (s, "⁢" , "<" ); replaceAll (s, ">" , ">" ); replaceAll (s, "&" , "&" ); replaceAll (s, " " , " " ); return s; }