另一种方法是一个简单的函数,它遍历源字符串,将不被删除的字符复制到目标字符串,如下所示。
char * CopyStringRemove(char *pDest, const char *pSrc)
{
// copy the source string, pSrc, to the destination string, pDest, while
// removing special codes that are between a < character and a | character.
// we will copy the two special code characters but remove everything in between.
char * pRet = pDest;
if (pDest) {
if (pSrc) {
int iState = 0; // state indicates whether copying characters or not.
for (; *pSrc; pSrc++) {
switch (*pSrc) {
case '<':
iState = 1; // indicate we are skipping characters
*pDest++ = *pSrc; // however copy this character we found
break;
case '|':
iState = 0; // indicate we are copying characters
break;
default:
break;
}
switch (iState) {
case 0:
*pDest++ = *pSrc; // state is to copy the current character
break;
case 1: // state is to not copy current character, just skip over it.
break;
}
}
}
*pDest = 0;
}
return pRet;
}
这个函数提供了相当大的灵活性,因为源可以是常数,也可以不是常数。目标可能是堆栈上的数组或从堆中分配的数组。如果源数组不是const,那么您可以通过调用CopyStringRemove() 函数进行就地更改,源和目标都是同一个缓冲区。
它还允许输入问题,例如没有“
一个测试工具,例如:
void testfunc(const char *buff)
{
{
char destbuff[128] = { 0 };
printf(" orig string \"%s\"\n", buff);
CopyStringRemove(destbuff, buff);
printf(" new \"%s\"\n", destbuff);
}
{
char destbuff[128] = { 0 };
char buff2[128] = { 0 };
strcpy_s(buff2, sizeof(buff2), buff);
printf(" orig string \"%s\"\n", buff2);
CopyStringRemove(destbuff, buff2);
printf(" new \"%s\"\n", destbuff);
}
{
char buff2[128] = { 0 };
strcpy_s(buff2, sizeof(buff2), buff);
printf(" orig string \"%s\"\n", buff2);
CopyStringRemove(buff2, buff2);
printf(" new \"%s\"\n", buff2);
}
}
void main_xfun(void)
{
char *buff = "cat -v < x y z | ";
char *buffa = "cat -v < x y z ";
char *buffb = "cat -v x y z | ";
char *buffc = "cat -v x y z ";
printf("\ntest #1\n");
testfunc(buff);
printf("\ntest #2\n");
testfunc(buffa);
printf("\ntest #3\n");
testfunc(buffb);
printf("\ntest #4\n");
testfunc(buffc);
}
产生以下结果:
test #1
orig string "cat -v < x y z | "
new "cat -v <| "
orig string "cat -v < x y z | "
new "cat -v <| "
orig string "cat -v < x y z | "
new "cat -v <| "
test #2
orig string "cat -v < x y z "
new "cat -v <"
orig string "cat -v < x y z "
new "cat -v <"
orig string "cat -v < x y z "
new "cat -v <"
test #3
orig string "cat -v x y z | "
new "cat -v x y z | "
orig string "cat -v x y z | "
new "cat -v x y z | "
orig string "cat -v x y z | "
new "cat -v x y z | "
test #4
orig string "cat -v x y z "
new "cat -v x y z "
orig string "cat -v x y z "
new "cat -v x y z "
orig string "cat -v x y z "
new "cat -v x y z "