求字串拼接问题代码
要求如下:
输入:
1,字串
2,字串个数
3,存放每个字窜相应首地址偏移量的指针
4,存放拼接后的字串的指针
(3,4,已经分配好足够的内存)
输出:拼接后字串的总长度。
函数形式如下:
#define MAXSTRLEN 10
int pinjiestrings(const char *input[MAXSTRLEN],const int count,int *poffset,char *output);
要求拼接後的总长度尽量短需要:
1,字串包含在另一字串中的保留最长的字串就可以了
调用代码如下:
Const char inputstr[][MAXSTRLEN]={
…
};
Main()
{
int count;
int totallen,ret;
int *poffs;
int *plens;
char *poutput;
int i;
count = sizeof(inputstr)/sizeof(inputstr[0]);
poffs = (int *)malloc(count * sizeof(int));
plens = (int *)malloc(count * sizeof(int));
poutput = (char *)malloc(count * (MAXSTRLEN+1));
totallen = 0;
for(i=0;i<count;i++)
{
plens[i]=strlen(inputstr[i]);
totallen += plens[i];
}
ret = pinjiestrings(inputstr,count,poffs,poutput);
ASSERT(ret<=totallen);
for(i=0;i<count;i++)
{
ASSERT(strncmp(poutput+poffs[i],inputstr[i],plens[i])==0);
}
free(poffs);
free(plens);
free(poutput);
}
对1字串在另一字串中的情况举例
Const char inputstr[][MAXSTRLEN]={
"ca",
"an",
"cang",
"ha"
};
当函数调用后:poffs[0] 应该=0,poffs[1] 应该=1,poffs[2] 应该=0,poffs[3]=4
poutput应该是"cangha",函数返回值应该是6