// // C++常用字符串操作函数的实现 // // // // // TODO: 等有空了又再补充其他的功能,当前的这几个 // @author norkts<[email protected]> // @version 0.1 norkts 2015-04-17 实现了字符串的splits, indexOf, trim, startsWith // #include <iostream> #include <vector> #include <string> using namespace std; namespace norkts{ class StringUtil{ public: StringUtil(string str){ this->str = str; } ~StringUtil(){ } /** * 分割字符串. * * @param string split 分隔符 */ vector<string> splits(string split){ return splits(str, split); } /** * 返回数组长度 . * */ int length(){ return str.length(); } /** * 去除多余的空格 */ string trim(){ str = trim(str); return str; } /** * 查找字符串,返回第一个匹配的位置 */ int indexOf(string search){ return indexOf(str, search); } /** * 是不是以字符串开头 */ bool startsWith(string search){ return startsWith(str, search); } string toString(){ return str; } public: /** * 同上功能的静态化 */ static int indexOf(string str, string search){ bool match = false; for(int i = 0; i < str.length() - search.length(); i++){ for(int j = 0; j < search.length(); j++){ if(search[j] != str[i + j]){ match = false; break; }else{ match = true; } } if(match){ return i; } } return -1; } /** * 去除头尾以及连续空白字符合并为1个 */ static string trim(string str){ while(str[0] == ' '){ memcpy((char *)str.c_str(), str.c_str() + 1, str.length()); } while(str[str.length() - 1] == ' '){ memset((char *)(str.c_str() + str.length() - 1), '\0', 1); } for(int i = 1; i < str.length() - 1; i++){ while(str[i] == ' ' && str[i + 1] == ' '){ memcpy((char *)(str.c_str() + i + 1) , (str.c_str() + i + 2), str.length() - i - 2); } } return str; } /** * 字符串分割 */ static vector<string> splits(string str, string split){ char* buff = new char[100]; vector<string> vts; int pos = 0; int end = 0; int slen = split.length(); string tempstr(str.c_str() + pos); tempstr = trim(tempstr); end = indexOf (tempstr, split); while(end > -1){ memset(buff, '\0', 100); memcpy(buff, tempstr.c_str(), end); vts.push_back(buff); cout << buff << endl; tempstr = string(tempstr.c_str() + end + slen); tempstr = trim(tempstr); end = indexOf(tempstr, split); if(end == -1){ vts.push_back(tempstr); } } return vts; } /** * 判断字符串是不是以search开头 */ static bool startsWith(string str, string search){ return indexOf(str, search) == 0; } private: string str; }; }; using namespace norkts; int main(){ StringUtil str(" driver=Firebird;Uid=SYSDBA; Pwd=masterkey;dbname=D:\\RXHOTEL.FDB; "); vector<string> res = str.splits(";"); cout << res.size() << endl; return 0; }
C++字符串常用操作函数
C++常用字符串操作函数,实现了字符串的分割,前向查找,去除空白等功能
猜你喜欢
转载自norkts.iteye.com/blog/2203155
今日推荐
周排行