#include "stdafx.h"#include "string.h"#include "conio.h"#include "math.h" int indexOf(unsigned char* src, unsigned char* find);int replace( char* src, char* find, char* rpc);int replaceAll( char* src, char* find, char* rpc); int indexOf(unsigned char* src, unsigned char* find) { int ret = -1; char* offsetPtr = NULL; if (src != NULL && find != NULL) { offsetPtr = strstr((char*)src, (char*)find); if (offsetPtr != NULL) { ret = strlen((char*)src) - strlen((char*)offsetPtr); } } return ret; } int replaceAll( char* src, char* find, char* rpc){ int pos = replace(src, find, rpc); if (pos != -1) { pos = replaceAll(src + pos + strlen(rpc), find, rpc); } return pos;} int replace( char* src, char* find, char* rpc){ int len = strlen(src); int pos = -1; int ptr = 0; int fndLen = strlen(find); int rpcLen = strlen(rpc); int moveDelta = rpcLen - fndLen; char* base = src; int moveBase = 0; int movePtr = 0; int moveCnt = 0; if (fndLen != 0 && (pos = indexOf((unsigned char*)base, (unsigned char*)find)) != -1 ) { moveCnt = len - pos - fndLen; for (ptr = 0; ptr <= moveCnt; ptr++) { moveBase = (moveDelta > 0? len : (pos + fndLen)); movePtr = moveBase + (-moveDelta / abs(moveDelta)) * ptr; src[moveDelta + movePtr] = src[movePtr]; } for (ptr = 0; ptr < rpcLen; ptr++) { src[pos + ptr] = rpc[ptr]; } } return pos;} int main(int argc, char* argv[]){ char src[500] = "This disambiguation page lists articles associated with the same title. If an internal link led you here, you may wish to change the link to point directly to the intended article"; char fnd[100] = "the"; char rpc[20] = "@"; printf("%s\n", src); replace(src, "the", "@"); printf("%s\n", src); replaceAll(src, "the", "@"); printf("%s\n", src); replaceAll(src, "to", "&"); printf("%s\n", src); replaceAll(src, "@", "the"); printf("%s\n", src); replaceAll(src, "&", "to"); printf("%s\n", src); getch(); return 0;} 运行结果: This disambiguation page lists articles associated with the same title. If an internal link led you here, you may wish to change the link to point directly to the intended articleThis disambiguation page lists articles associated with @ same title. If an internal link led you here, you may wish to change the link to point directly to the intended articleThis disambiguation page lists articles associated with @ same title. If an internal link led you here, you may wish to change @ link to point directly to @ intended articleThis disambiguation page lists articles associated with @ same title. If an internal link led you here, you may wish & change @ link & point directly & @ intended articleThis disambiguation page lists articles associated with the same title. If an internal link led you here, you may wish & change the link & point directly & theintended articleThis disambiguation page lists articles associated with the same title. If an internal link led you here, you may wish to change the link to point directly to the intended article

评论