说明:
如同C++中的string类型、VC++中CString类型、Objective-C的NSStringd等字符串类中的获取子串的方法,C语言版可以通用于各大平台,方便进行代码移植。
测试环境:
操作系统: Windows10 64位
运行环境: Visual Studio 10
依赖的头文件:
#include <string.h>
#include <stdlib.h>
函数:
/***************************************************************
/* 函 数 名:GetSubstring
/* 函数功能:C语言版,获得字符串中指定位置的子串
/* 参 数:
/* strSource:源字符串
/* uStartPos:子串在源串的起始位置
/* uEndPos: 子串在源串的结束位置
/* 返 回 值:
/* 如果成功,则返回子串
/* 如果失败,则返回空串
/*
/* 作 者:X攻城狮
/* 日 期:2015年11月4日
/***************************************************************/
char* GetSubstring(const char *strSource, const unsigned int uStartPos, const unsigned int uEndPos)
{
unsigned int uLen = strlen(strSource);
if (uLen == 0)
{
return "";
}
char *strTemp = (char *)malloc(uLen+1);
memset(strTemp, 0, uLen+1);
strcpy(strTemp, strSource);
if(uStartPos > uLen)
{
free(strTemp);
return "";
}
uLen = uEndPos - uStartPos;
char *strSub = (char *)malloc(uLen+1);
memset(strSub, 0, uLen+1);
unsigned int i;
for(i=0; i<=uLen; i++)
{
strSub[i] = strTemp[uStartPos + i];
}
strSub[i] = '\0';
free(strTemp);
return strSub;
}