思路:使用strstr,从左向右依次查找,找到最后出现的那个。从右向左找也行(也许更快),实现起来比较麻烦,没有这个易懂。
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> char* taishan_strrstr(const char *pSrc, const char* pSub) { assert(pSrc); assert(pSub); char* pLastFound = NULL; char* pTemp = (char*)pSrc; int nSubLen = strlen(pSub); if( pSrc == NULL || pSrc[0] == 0 || pSub == NULL || pSub[0] == 0) { return NULL; } while (pTemp) { pTemp = strstr(pTemp, pSub); if (!pTemp) { break; } pLastFound = pTemp; pTemp += nSubLen; } return pLastFound; } int main() { const char* pSrc = "Taishan Office, Tai'an"; const char* pSub = "Tai"; char* pRight = taishan_strrstr(pSrc, pSub); printf("right found=%s\n", pRight); return 0; }