linux c/c++ 字符串 操作之 split

linux c 字符串 操作之 分割 split

=====================================

#include

#include
/**
 * 分割字符串成二维数组
 * 可根据传入分割符来计算出二维数组长度大小
 * @param msg --需要分割的字符串
 * @param splitChar -- 用于分割字符串的字符
 * @param arrLen -- 返回二维数据的长度,用于遍历
 * @return  字符二维数组
 */
char** splitStr(const char *msg, char splitChar, int *arrLen)
{
int pos = 0;
const char *tmp = msg;
int tmpArrLen =1;
int maxStrLen = 0;
int tmpStrLen = 0;
while(*tmp != '\0')
{
if(*tmp == splitChar)
{
tmpStrLen = 0;
tmpArrLen++;
}
else
{
tmpStrLen++;
if(tmpStrLen > maxStrLen)
{
maxStrLen = tmpStrLen; //get the max string length
}
}
tmp++;
}
if(tmpArrLen == 0)
{
*arrLen = 0;
return NULL;
}
*arrLen = tmpArrLen;
printf("arrLen=%d, maxStrLen=%d\n", *arrLen ,maxStrLen);
maxStrLen=maxStrLen+1; //多加1 用于存放 \0结束符
char **retArr = (char **)malloc( sizeof(char) * tmpArrLen);
int i=0;
for(i=0; i < tmpArrLen; i++)
{
retArr[i] = (char *)malloc(maxStrLen);
}


tmp = msg;
i= 0;
int j=0;
while(*tmp != '\0')
{
if(*tmp == splitChar)
{
retArr[i][j] = '\0';
i++;
j=0;
}
else
{
retArr[i][j] = *tmp;
j++;
if(j>=maxStrLen)
{
retArr[i][j-1] = '\0';
j--;
}
}
tmp++;
}
retArr[i][j] = '\0';


return retArr;
}
int main()
{
const char msg[]={"aaaaa,bbbbbbbb,cc"};
int arrLen=0;
char** strArr = splitStr(msg, ',', &arrLen);
if(strArr != NULL)
{
int i=0;
for(i=0; i< arrLen; i++)
{
printf("strArr[%d]=%s\n", i, strArr[i]); //遍历
}
}
//释放空间
int i=0;
for(i=0; i< arrLen; i++)
{
free(strArr[i]);
}
free(strArr);

}

==================================================================

linux c++ 字符串 操作之 split


#include
#include
#include

using namespace std;
/**
 * Split string to array
 * @param str -- the string need to be splited.
 * @param vec -- vector use to store splited string item.
 * @param splitChar -- the split character
 */
void splitStr(const string &str, vector &vec, const string &splitChar)
{
string::size_type pos = str.find(splitChar);
string::size_type pos1 = 0;
while(string::npos !=  pos)
{
vec.push_back(str.substr(pos1, pos -pos1));
pos1 = pos + splitChar.size();
pos = str.find(splitChar, pos1);
}
if(pos1 != str.length())
{
vec.push_back(str.substr(pos1));
}
}


int main()
{
string msg = "aaaaa,bbbbbbbb,cc";

//分割
vector vec;
splitStr(msg, vec, ",");

//遍历
int i=0;
for(i=0; i< vec.size(); i++)
{
cout << vec[i] << endl;
}
}



你可能感兴趣的:(c/c++)