在global.h中添加代码 /* * @param char* dest 目标串,也就是替换后的新串 * @param const char* src 源字符串,被替换的字符串 * @param const char* oldstr 旧的子串,将被替换的子串 * @param const char* newstr 新的子串 * @param int len 将要被替换的前len个字符 */ char *lr_strreplace(char *dest, char *src, const char *oldstr, const char *newstr, size_t len){ char *needle; //子串位置指针 char *tmp; //临时内存区 //如果串相等,则直接返回 if(strcmp(oldstr, newstr)==0){ return src; } dest = src; //把源串地址赋给指针dest,即让dest和src都指向src的内存区域 //如果找到子串, 并且子串位置在前len个子串范围内, 则进行替换, 否则直接返回 while((needle = (char *) strstr(dest, oldstr)) && (needle -dest <= len)){ //分配新的空间: +1 是为了添加串尾的' '结束符 tmp=(char*)malloc(strlen(dest)+(strlen(newstr)-strlen(oldstr))+1); strncpy(tmp, dest, needle-dest); //把src内的前needle-dest个内存空间的数据,拷贝到arr tmp[needle-dest]=' '; //标识串结束 strcat(tmp, newstr); //连接arr和newstr, 即把newstr附在arr尾部, 从而组成新串(或说字符数组)arr strcat(tmp, needle+strlen(oldstr)); //把src中 从oldstr子串位置后的部分和arr连接在一起,组成新串arr dest = (char *)strdup(tmp); //把用malloc分配的内存,复制给指针retv free(tmp); //释放malloc分配的内存空间 } return dest; }
在Action中调用
Action() { //11041331","11041372","11041373","11041374 //11041331|11041372|11041373|11041374 char *str; char *old="",""; //需要替换的字符串"," char *new="|"; char *dest; lr_save_string("11041331","11041372","11041373","11041374", "src"); str=lr_eval_string("{src}"); lr_output_message("替换前的字符串=%s",lr_eval_string("{src}")); lr_output_message("替换后的字符串=%s",lr_strreplace(dest,str,old,new,strlen(str))); return 0; }
补充:
int main() { char *str="http://192.168.1.1:58763/result.xml"; char *old="192.168.1.1"; char *new="127.0.0.1"; char *dest; //分配内存空间: 大小 == src的长度 + newstr和oldstr长度差(可能是正负或0)+1 printf("%s ",strreplace(dest, str, old, new,1)); printf("%s ",strreplace(dest, str, old, new,5)); printf("%s ",strreplace(dest, str, old, new,9)); printf("%s ",strreplace(dest, str, old, new,11)); printf("%s ",strreplace(dest, str, old, new,40)); if(dest) { free(dest); } return 0; }