C++ 對字串處理方式整理
阿新 • • 發佈:2019-01-05
判斷字元是英文還是漢字
/*
brief 判斷字元是英文還是漢字
param ch 字元(位元組)
return true:是英文;false:是中文
*/
static bool isEnglishChar(char ch)
{
/*漢字的三個位元組(有些編碼格式是兩個位元組)的最高為都為1,這裡採用判斷最高位的方法
將ch位元組進行移位運算,右移8位,這樣,如果移位後是0,
則說明原來的位元組最高位為0,不是1那麼也就不是漢字的一個位元組
*/
if (~(ch >> 8) == 0)
{
return false; //代表不是漢字
}
return true;
}
判斷字元是英文還是漢字
//是否是漢字
static bool IsChinese(std::string strBuffer)
{
if (strBuffer == "")
{
return false;
}
for (int i = 0; i < strBuffer.length()-1; i++)
{
if (!isEnglishChar(strBuffer.at(i)))
{
return true;
}
}
return false;
}
獲取剪下排除emoji表情的字串
//獲取剪下排除emoji表情的字串
static std::string GetStringByCutEmoji(std::string strValue)
{
int size = strValue.size();
std::string result = "";
if (size > 0)
{
for (int i = 0; i < size; i++)
{
//是否是英文
if (isEnglishChar(strValue[i]))
{
result.push_back(strValue[i]);
}
else
{
if ((unsigned)(strValue[i] & 0xf0) == 0xe0)
{
for (int j = 0; j < CHINESE_CHAR_LENGTH_UTF8; ++j)
{
result.push_back(strValue[i + j]);
}
i += CHINESE_CHAR_LENGTH_UTF8 - 1;
}
}
}
}
return result.c_str();
}
擷取字串
/*
brief 擷取字串
param start 起始下標,從1開始
param end 結束下標
param isNeedPoint 是否需要在末尾新增“...”
return 擷取之後的字串
*/
static std::string CutStringUtil(std::string util,int start, int end, bool isNeedPoint)
{
//CCLOG("util = %d", util.length());
util = GetStringByCutEmoji(util);
if ( util.length() <= 0 || start >= end )
return util;
std::vector<std::string> _result;
int i = 0;
while (i < util.length())
{
if (!isEnglishChar(util.at(i)))
{
_result.push_back(util.substr(i, CHINESE_CHAR_LENGTH_UTF8)); // 一個漢字三個位元組
i = i + CHINESE_CHAR_LENGTH_UTF8;
}
else
{
_result.push_back(util.substr(i, 1)); // 一個英文一個位元組
i = i + 1;
}
}
if (start >= 1 && _result.size() <= start)return util;
// 容錯處理,如果end大於字串長度,則捨棄多餘部分
end = _result.size() >= end ? end : _result.size();
std::string temp = "";
//直接從_result裡取即可
int max = end * 2;
int curValue = 0;
int enIdx = 0;
for (int i = start; i < end; i++)
{
if (i > _result.size() - 1 || curValue >= max)
{
break;
}
temp += _result[i];
//CCLOG("_result[%d] = %s", i, _result[i].c_str());
if (!IsChinese(_result[i].c_str()))
{
curValue++;
if (++enIdx % 2 == 0)
end++;
}
else
{
curValue += 2;
}
}
// 如果字串太長,在末尾新增“...”
if (isNeedPoint)
{
if (_result.size() > end)
{
temp += "...";
}
}
//CCLOG("temp = %s", temp.c_str());
return temp;
}
//判斷是不是整形
static bool IsINT(const char *str)
{
for (int i = 0; i < strlen(str); i++)
if (str[i] < '0' || str[i] > '9')
return false;
return true;
}