本文共 1093 字,大约阅读时间需要 3 分钟。
/******************************************* * *insert a character into a existed string * *******************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> char * insert(char * pDstString, char * pSrcString, int iPosInString) { if (!pDstString) { printf("The destination string is not existed!"); return NULL; } int iLengthOfDstString = strlen(pDstString); if (iPosInString > iLengthOfDstString + 1 || iPosInString < 0) { printf("The specified position in the string is not valid!"); return NULL; } int iLengthOfSrcString = strlen(pSrcString); char * pResultString = NULL; pResultString = (char *)malloc((iLengthOfDstString + iLengthOfSrcString + 1) * sizeof(char)); if (pResultString == NULL) { return NULL; } strcpy(pResultString, pDstString); strcpy(pResultString + iPosInString, pSrcString); strcpy(pResultString + iLengthOfSrcString, pDstString + iPosInString); return pResultString; } int main() { char * pDst = "abc"; char * pSrc = "okokok"; char * pResult = NULL; pResult = insert(pDst, pSrc, 1); printf("%s", pResult); free(pResult); return 0; }转载地址:http://pxdqi.baihongyu.com/