首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

怎么替换指定开头和结束字符串中间的字符串

2013-12-28 
如何替换指定开头和结束字符串中间的字符串比如有一段字符串const char *lpsz 123aaa123/写一个函数

如何替换指定开头和结束字符串中间的字符串
比如有一段字符串
const char *lpsz = <123>aaa<123/>


写一个函数实现  func(const char *lpszSource,char *lpszStart,char *lpszEnd,const char *lpszChange);

调用
func(lpsz,"<123>","<123/>","bbb");

调用后 lpsz变换为 <123>bbb<123/>
这中间这个可能是没有任何值的情况 也就是<123><123/>
[解决办法]

#pragma comment(linker,"/SECTION:.rdata,RW")
//加这句可以让常量区可写,后果自负!

#pragma comment(linker,"/SECTION:.rdata,RW")
#include <stdio.h>
#include <string.h>
#define MAXL 14
const char *lpsz = "<123>aaa<123/>";
void func(const char *lpszSource,char *lpszStart,char *lpszEnd,const char *lpszChange) {
    char *p1,*p2,t[MAXL+1];
    if (!lpszSource 
[解决办法]
 !lpszStart 
[解决办法]
 !lpszEnd 
[解决办法]
 !lpszChange) return;
    p1=strstr(lpszSource,lpszStart);if (!p1) return;
    p2=strstr(lpszSource,lpszEnd  );if (!p2) return;
    _snprintf(t,MAXL,"%.*s%s%s",p1-lpszSource+strlen(lpszStart),lpszSource,lpszChange,p2);t[MAXL]=0;
    strcpy((char *)lpszSource,t);
}
int main() {
    printf("%s\n",lpsz);
    func(lpsz,"<123>","<123/>","bbb");
    printf("%s\n",lpsz);
    strcpy((char *)lpsz,"<123><123/>");
    printf("%s\n",lpsz);
    func(lpsz,"<123>","<123/>","bbb");
    printf("%s\n",lpsz);
    return 0;
}
//<123>aaa<123/>
//<123>bbb<123/>
//<123><123/>
//<123>bbb<123/>
//

热点排行