函数功能:在一个字符串中截取用户指定开始位置和长度的子串;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 120
/***************************************************************************
函数功能:在字符串特定位置开始截取指定长度的子串
函数参数:srcStr:原串; startPos:在原串中截取的起始位置;
cutLength:截取长度,长度若过大,则截取到原串末尾;
函数返回:成功:返回截取到的字串; 其它:返回NULL;
****************************************************************************/
char *substr(const char* srcStr, int startPos, int cutLength);
int main()
{
printf("Please enter a string here.\n");
char strArray[MAX_LEN] = {0};
fgets(strArray, MAX_LEN, stdin);
char *destStr = NULL;
int startPos = 0, cutLength = 0;
printf("Please intput the startPos and cutLength in here.\n");
scanf("%d%d", &startPos, &cutLength);
destStr = substr(strArray, startPos, cutLength);
if (destStr) {
printf("The src string is: %s, from %d pos cut %d characters, the deststr is: %s\n", strArray, startPos, cutLength, destStr);
}
return 0;
}
char *substr(const char* srcStr, int startPos, int cutLength)
{
if (startPos < 0 || cutLength < 0 ) {
printf("Please check that your parameters are correct.\n");
return NULL;
}
int index = 0;
static char destArray[MAX_LEN] = {0};
// 偏移至字符串中要开始截取的位置
srcStr = srcStr + startPos;
while (srcStr && index < cutLength) {
destArray[index] = *srcStr++;
if (*srcStr == '\0') {
break;
}
index++;
}
return destArray;
}
结果演示:
在终端根据提示输入相应的字符串,开始截取位置,截取长度等信息进行测试;