C++之string位置、字节数转换
1.通过文本和距离文本起始处位置获取距离起始处字节数
unsigned int GetTextIndex(const string& strText, unsigned int nPos)
{
unsigned int nResult = 0;
while(nPos > 0)
{
if (strText[nResult] & 0x80) //中文
{
nResult += 2;
nPos--;
}
else
{
nResult++;
nPos--;
}
//处理特殊情况
if (nResult >= strText.length())
{
nResult = strText.length();
break;
}
}
return nResult;
}
2.通过文本和距离起始处字节数获取距离文本起始处位置
int GetPositionByTextIndex(const string& strText, int nIndex)
{
int nResult = 0;
int nPos = 0;
if (strText.length() == 0)
{
return 0;
}
while(nIndex >= 0)
{
if (strText[nPos] & 0x80) //中文
{
nPos += 2;
nIndex -= 2;
nResult++;
}
else
{
nPos++;
nIndex--;
nResult++;
}
//处理特殊情况
if (nPos >= strText.length())
{
break;
}
}
return nResult;
}