- void CWebTransfer::Substitute(char *pInput, char *pOutput, char *pSrc, char *pDst)
- {
- char *pi, *po, *p;
- int nSrcLen, nDstLen, nLen;
- // 指向输入字符串的游动指针.
- pi = pInput;
- // 指向输出字符串的游动指针.
- po = pOutput;
- // 计算被替换串和替换串的长度.
- nSrcLen = strlen(pSrc);
- nDstLen = strlen(pDst);
- // 查找pi指向字符串中第一次出现替换串的位置,并返回指针(找不到则返回null).
- p = strstr(pi, pSrc);
- if(p)
- {
- // 找到.
- while(p)
- {
- // 计算被替换串前边字符串的长度.
- nLen = (int)(p - pi);
- // 复制到输出字符串.
- memcpy(po, pi, nLen);
- memcpy(po + nLen, pDst, nDstLen);
- // 跳过被替换串.
- ppi = p + nSrcLen;
- // 调整指向输出串的指针位置.
- popo = po + nLen + nDstLen;
- // 继续查找.
- p = strstr(pi, pSrc);
- }
- // 复制剩余字符串.
- strcpy(po, pi);
- }
- else
- {
- // 没有找到则原样复制.
- strcpy(po, pi);
- }
- }
为了替换,你必须先找到要替换的串的位置。
string s( "abcdefg ");
string::size_type sz = s.find( "def ");
// 验证确实找到了
if (sz != string::npos)
{
s.replace(sz, 3, "yxz ");
}
string s( "abcdefg ");
string::size_type sz = s.find( "def ");
// 验证确实找到了
if (sz != string::npos)
{
s.replace(sz, 3, "yxz ");
}
试试这个函数。更多精彩,尽在:http://blog.youkuaiyun.com/mxclxp/archive/2004/08/25/84818.aspx(原创!!)
//////////////////////////////////////////////////////////////////////////
/*
* 功能: 把 "原始串 " 中所有的 "替换源串 " 替换成 "替换目的串 ",返回替换完
的结果。
* 意义: 此功能解决了 std::string 中替换功能的单一,方便了编程。
*/
//////////////////////////////////////////////////////////////////////////
std::string stringReplace(const std::string& input, // 原始串
const std::string& find, // 替换源串
const std::string& replaceWith) // 替换目的串
{
std::string strOut(input);
int curPos = 0;
int pos;
while((pos = strOut.find(find, curPos)) != -1)
{
strOut.replace(pos, find.size(), replaceWith); // 一次替换
curPos = pos + replaceWith.size(); // 防止循环替换!!
}
return strOut;
}
//////////////////////////////////////////////////////////////////////////
/*
* 功能: 把 "原始串 " 中所有的 "替换源串 " 替换成 "替换目的串 ",返回替换完
的结果。
* 意义: 此功能解决了 std::string 中替换功能的单一,方便了编程。
*/
//////////////////////////////////////////////////////////////////////////
std::string stringReplace(const std::string& input, // 原始串
const std::string& find, // 替换源串
const std::string& replaceWith) // 替换目的串
{
std::string strOut(input);
int curPos = 0;
int pos;
while((pos = strOut.find(find, curPos)) != -1)
{
strOut.replace(pos, find.size(), replaceWith); // 一次替换
curPos = pos + replaceWith.size(); // 防止循环替换!!
}
return strOut;
}