/*
* 【功能】 对源字符串中得字符串进行查找替换 并返回动态申请空间的指针 char* Fun(char* pSrc, char* pOldStr, char* pNewStr);
* 【输入】pSrc 源字符串
* pOldStr 需要被替换的字符串
* pNewStr 替换的新的字符串
* 【返回】替换后的新的字符串的指针
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
//计算字符串长度
int lenString(char * str)
{
int i = 0;
while(str[i] != '\0')
{
i++;
}
return i;
}
//查找符合条件的字符串
int findString(int startPosition, char *pSrc, char *pOldStr)
{
int i = 0, position;
while(pSrc[startPosition] != '\0' && pOldStr[i] != '\0')
{
if(pSrc[startPosition] == pOldStr[i])
{
startPosition++;
i++;
}
else if(pSrc[startPosition] == pOldStr[0])
{
position = startPosition + 1;
startPosition++;
i = 1;
}
else
{
position = startPosition + 2;
startPosition++;
i = 0;
}
}
if(pOldStr[i] != '\0')
{
position = 0;
return -1;
}
return position;
}
//替换字符
void repalceString(char * resultStr, char *pSrc, int len_OldStr, char *pNewStr, int position)
{
int i = 0, j = 0, k = 0;
while(pSrc[i] != '\0')
{
if(i == position -1)
{
while(pNewStr[j] != '\0')
{
resultStr[k] = pNewStr[j];
j++;
k++;
}
i += len_OldStr;
}
else
{
resultStr[k] = pSrc[i];
i++;
k++;
}
}
resultStr[k] = '\0';
}
char * Fun(char *pSrc, char *pOldStr, char *pNewStr)
{
int len_Src, len_OldStr, len_NewStr;
char *resultStr;
int count[MAX]; //记录符合替换的字符位置
int i = 0, startPosition = 0, position ,number;
char *pSrc1;
len_Src = lenString(pSrc);
len_OldStr = lenString(pOldStr);
len_NewStr = lenString(pNewStr);
//查找字符串
while(1)
{
position = findString(startPosition, pSrc, pOldStr);
if(position == -1)
break;
else
{
count[i] = position;
startPosition = position + len_OldStr -1;
i++;
}
}
count[i] = -1;
//替换字符串
pSrc1 = (char *)malloc(len_Src + i * (len_NewStr - len_OldStr));
memcpy(pSrc1, pSrc, len_Src);
resultStr = (char *)malloc(len_Src + i * (len_NewStr - len_OldStr));
i = 0;
while(count[i] != -1)
{
repalceString(resultStr, pSrc1, len_OldStr, pNewStr, count[i]);
memcpy(pSrc1, resultStr, sizeof(resultStr));
i++;
}
return resultStr;
}
int main()
{
char *pSrc = "aassdddffgghhaassdddffgg", *pOldStr = "dd", *pNewStr = "^_^";
char *Result;
Result = Fun(pSrc, pOldStr, pNewStr);
printf("源字符串:%s\n需要替换的字符串:%s\n替换成字符串:%s\n", pSrc, pOldStr, pNewStr);
if(Result == NULL)
printf("没有找到需要替换的字符串\n");
else
printf("结果:%s\n", Result);
return 0;
}
源字符串中得字符串进行查找替换
最新推荐文章于 2022-09-05 20:41:51 发布