字符串查找和替換算法
#include <stdio.h> #include <string.h> /************************************************************************/ /* 功能:實現字符串的查找和替換,所有被替換串出現的地方都用替換串替換 /* 參數:pSrc--指向源字符串 /* pDst--指向替換完成後的字符串,並作為輸出參數 /* pOldString--指向被替換字符串 /* pNewString--指向替換字符串 /************************************************************************/ void FindAndReplace(char *pSrc, char *pDst, char *pOldString, char *pNewString) { char *pInput = pSrc, // 指向源字符串的遊動指針 *pOutput = pDst,// 指向目標字符串(即替換後的字符串)的遊動指針 *p = NULL; // 指向查找到的字符串的位置的指針 int nOldStringLen= strlen(pOldString); // 被替換字符串的長度 int nNewStringLen = strlen(pNewString); // 替換字符串的長度 int nLen; // 查找被替換字符串在源字符串中第一次出現的位置 p = strstr(pInput, pOldString); if (p) // 如果找到了 { while (p) { // 計算被替換串前邊字符串的長度. nLen = (int)(p - pInput); // 將被替換字符串首次出現前的字符串複製到輸出字符串中 memcpy(pOutput, pInput, nLen); // 將替換串複製到輸出串中 memcpy(pOutput + nLen, pNewString, nNewStringLen); // 跳過被替換串的位置 pInput = p + nLen; // 調整指向輸出串的位置 pOutput = pOutput + nLen + nNewStringLen; // 繼續往下查找 p = strstr(pInput, pOldString); } // 將剩餘部分複製到輸出串中 strcpy(pOutput, pInput); } else // 如果被替換串不在源字符串中出現,則返回源字符串 { strcpy(pDst, pSrc); } } int main() { char src[] = "abcdesdesdrsdsdse"; char dst[100]; FindAndReplace(src, dst, "sd", "ILOVEYOU"); printf("%s\n", dst); return 0; }
最後更新:2017-04-03 18:52:05