• 一道C++练习题,替换一个字符串里所有实例


    做了一道C++练习题,替换一个字符串里面的所有实例。

    #include <iostream>
    #include <string>
    using namespace std;
    
    const int NOT_FOUND = -1;
    int strFind(string str, string strSub);
    string strRepIdx(string strDes, int idxStart, int idxEnd, string strRepDes);
    string strRep(string strDes, string strRepSrc, string strRepDes);
    
    // Replace all instances of strRepSrc in strDes with strRepDes and return the string replaced;
    string strRep(string strDes, string strRepSrc, string strRepDes)
    {
    	int nIdxFound = strFind(strDes, strRepSrc);
    	if (NOT_FOUND == nIdxFound)
    	{
    		return strDes;
    	}
    	else
    	{
    		string strLeft = strDes.substr(nIdxFound+ strRepSrc.length(),strDes.length()-nIdxFound);
    		string strTemp = strRepIdx(strDes, nIdxFound, nIdxFound + strRepSrc.length()-1, strRepDes);
    		return strTemp.substr(0, nIdxFound + strRepDes.length()) + strRep(strLeft,strRepSrc,strRepDes);
    
    	}
    	return strDes;
    }
    
    // find index of substring strSub in string str;
    // return:
    //			-1,for not found
    //			0 or positive int, index of substring 
    int strFind(string str, string strSub)
    {
    	int strLen = str.length();
    	int subStrLen = strSub.length();
    	if (strLen < subStrLen)
    	{
    		return NOT_FOUND;
    	}
    	else
    	{
    		for (int i = 0; i < strLen - subStrLen+1; i++)
    		{
    			if (str.substr(i, subStrLen) == strSub)
    			{
    				return i;
    			}
    		}
    	}
    	return NOT_FOUND;
    }
    
    string strRepIdx(string strDes, int idxStart, int idxEnd, string strRepDes)
    {
    	strDes = strDes.substr(0, idxStart) + strRepDes + strDes.substr(idxEnd+1, strDes.length());
    	return strDes;
    }
    
    int main()
    {
    	string str0 = "Hello World";
    	string subStr1 = "World";
    	string subStr2 = "l";
    	string subStrDes = "ii";
    
    	cout << "Origin String is " << str0 << endl;
    	cout << "Replace " << subStr1 << " with " << subStrDes << " is " << strRep(str0, subStr1, subStrDes) << endl;
    	string strRep2 = strRep(str0, subStr2, subStrDes);
    	cout << "Replace " << subStr2 << " with " << subStrDes << " is " << strRep2 << endl;
    
    	return 0;
    }
    

    感觉基础的编码水平还基本停留在大一学C语言时候……┗|`O′|┛ 。 

  • 相关阅读:
    shell:echo -e "33字体颜色"
    Linux配置swap
    软工2017第三周作业——词频效能分析
    ffmpeg——关于视频压缩
    软件工程2017第一次作业——随笔汇总
    软件工程2017第一次作业——随笔二
    软件工程2017第一次作业——随笔一
    02-分支结构
    iOS中如何知道app版本已更新
    socket编程中客户端常用函数 以及简单实现
  • 原文地址:https://www.cnblogs.com/spyplus/p/7554476.html
Copyright © 2020-2023  润新知