ProcessString.h
//Linux & C++11
#pragma once
//包含系统头文件
#include <string>
#include <sstream>
#include <vector>
//宏定义:参数流向
#define IN
#define OUT
#define INOUT
//使用命名
using std::string;
using std::istringstream;
using std::vector;
namespace sinicheveen
{
class ProcessString
{
public:
//group 1:判断型函数
//判断一个字符串是不是数字字符串
//e.g. "023456789" --> true; "12A56" --> false
static bool isNumString(IN const string& strIn);
//判断一个字符串是不是以逗号分隔的数字字符串,且字符串最后一个字符不能是逗号,中间不能有空格
//e.g. "1,2,3,4" --> true; "1,3.14,9" --> true; "1,2,3,4," --> false; "1,A,5" --> false
static bool isNumStringWithComma(IN const string& strIn);
//判断一个字符串是不是以某种分隔符分隔的数字字符串,且字符串最后一个字符不能是分隔符,中间不能有空格
//e.g. "1,2,3,4" --> true; "1,3.14,9" --> true; "1,2,3,4," --> false; "1,A,5" --> false
static bool isNumStringWithSeparator(IN const string& strIn, IN const char cSeparator = ',');
//group 2:字符串转数字
/*
*Name:stringToNumber
*Description:字符串转数字
*Input:IN const string& strIn,一个字符串
*Return:T:转换后的数字
*Caution:
*/
template<typename T>
T stringToNumber(IN const string& strIn)
{
istringstream iss(strIn);
T num;
iss >> num;
return num;
} //stringToNumber()
/*
*Name:extractNumFromString
*Description:从数字字符串中提取出数字
*Input:IN const string& strIn,以分隔符分隔的一个数字字符串
* OUT vector<T>& vExtractedNums,提取出的数字
* IN const char cSeparator = ',',数字之间的分隔符,默认是英文逗号
*Return:bool,成功返回 true,失败返回 false
*Caution:
*/
template <typename T>
bool extractNumFromString(IN const string& strIn, OUT vector<T>& vExtractedNums, IN const char cSeparator = ',')
{
//判断是不是数字字符串
for (const auto& iChar : strIn)
{
if ((iChar >= '0' && iChar <= '9') || iChar == '.' || iChar == cSeparator)
{
continue;
}
else
{
return false;
}
}
//提取数字
size_t startPos = 0;
do
{
size_t endPos = strIn.find(cSeparator, startPos);
if (endPos != string::npos)
{
string strNum;
strNum.assign(strIn, startPos, endPos - startPos);
T num;
num = stringToNumber<T>(strNum);
vExtractedNums.push_back(num);
startPos = endPos + 1;
if (startPos > (strIn.size() - 1))
{
break;
}
}
else
{
string strNum;
strNum.assign(strIn, startPos, strIn.size() - startPos);
T num;
num = stringToNumber<T>(strNum);
vExtractedNums.push_back(num);
break;
}
} while (1);
return true;
} //extractNumFromString()
//group 3:格式处理函数
//移除行首和行尾的空白字符
static void rmSpaceInBegAndEnd(INOUT string& strIn);
//gruop 4:从键盘读取
//从键盘读取一行字符串,直到遇到 \n 为止,中间遇到其它空白字符,仍继续
static void readStringEndByEnter(OUT string& strWhatRead);
//从键盘读取一行字符串,直到遇到多个 \n 为止(由用户定义个数),中间遇到其它空白字符,仍继续
static void readStringEndByMultiEnter(OUT string& strWhatRead, IN const int32_t numOfEnter = 2);
//group 5:字符串分隔
//分隔 C 风格字符串
static void spliceString(IN char* pcStrIn, OUT vector<string>& vSubStrings, IN const char* pcSepartor);
}; //ProcessString
} //sinicheveen
未完 ......
点击访问原文(进入后根据右侧标签,快速定位到本文)