C++字符串常用操作函数

C++常用字符串操作函数,实现了字符串的分割,前向查找,去除空白等功能
[code]
//
// C++常用字符串操作函数的实现
//
//
//
//
// TODO: 等有空了又再补充其他的功能,当前的这几个
// @author norkts<norkts@gmail.com>
// @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;
}

[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值