使用C语言编写函数,从字符串指定位置开始删除指定长度字串,如:“abcdefg”,从第3位开始删除3个字符,输出为:“abfg”。
思路:删除的起始数组下标为:nPos -1,跳过删除字串,下一个字符数组下标:nPos + n - 1,将nPos + n - 1位置开始的字符往nPos -1处赋值,下标+1,循环操作,直到遇到字符串结束符,注意:针对新的字符串最后一位加上'\0'。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int delete_sub_str(char* pStr, int nPos, int n)
{
int nLen = strlen(pStr);
//nPos应小于字符串长度,n最大应该是:字符串长度 - 起始位置 + 1
if ((nPos < 0) || (n <= 0) || (nPos >= nLen) || (n > nLen - nPos + 1)) {
return -1;
}
int i = nPos -1; //删除字符串起始下标
int j = nPos + n - 1; //删除字串结束下标后一位
while (pStr[j] != '\0') {
pStr[i++] = pStr[j++];
}
//字符串剩余长度:nLen - n
pStr[nLen - n] = '\0';
return 0;
}
int main()
{
//abcdefg --> abfg
char szBuf[32] = { 0 };
strcpy(szBuf, "abcdefg");
delete_sub_str(szBuf, 3, 3);
printf("szBuf = [%s]\n", szBuf);
return 0;
}
|