---
title: "C++字符串常用操作函数"
author: "norkts"
date: "2015-04-17T01:30:16Z"
tags: ["C++"]
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2015-04-17T01:30:16Z"
id: 2203155
url: "https://norkts.iteye.com/blog/2203155"
---

C++常用字符串操作函数，实现了字符串的分割，前向查找，去除空白等功能 \[code] // // C++常用字符串操作函数的实现 // // // // // TODO: 等有空了又再补充其他的功能，当前的这几个 // @author norkts // @version 0.1 norkts 2015-04-17 实现了字符串的splits, indexOf, trim, startsWith // #include #include #include using namespace std; namespace norkts{ class StringUtil{ public: StringUtil(string str){ this-&gt;str = str; } ~StringUtil(){ } /\** * 分割字符串. * * @param string split 分隔符 \*/ vector 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 &lt; str.length() - search.length(); i++){ for(int j = 0; j &lt; 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 &lt; 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 splits(string str, string split){ char* buff = new char\[100]; vector 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 &gt; -1){ memset(buff, '\\0', 100); memcpy(buff, tempstr.c\_str(), end); vts.push\_back(buff); cout &lt;&lt; buff &lt;&lt; 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 res = str.splits(";"); cout &lt;&lt; res.size() &lt;&lt; endl; return 0; } \[/code]