zoukankan      html  css  js  c++  java
  • C++primer 9.43

    题目要求:编写一个函数,接受三个string参数s,oldVal和newVal。使用迭代器及insert和erase函数将s中所有oldVal替换为newVal。测试你的程序,用它替换通用的简写形式,如,将"tho"替换为"though",将"thru"替换为"though"。

    #include<iostream>
    #include<string>
    #include<vector>
    #include<sstream>
    using namespace std;
    
    void find_replace(string s, string oldValue, string newValue)
    {	
    	if (s.empty() || oldValue.empty() || newValue.empty())
    	{
    		cout << "Error" << endl;
    		return;
    	}
    	if (s.size() < newValue.size())
    	{
    		cout << "Error" << endl;
    		return;
    	}
    
    	string word;
    	vector<string>vec;
    
    	//分割string
    	istringstream stream(s);
    	{
    		while(stream >> word)
    		   vec.push_back(word);
    	}
    
    
    	vector<string>::iterator it1 = vec.begin();
    
    	while (it1 != vec.end())
    	{
    		if (*it1 == oldValue)
    		{
    			string::iterator it2 = (*it1).begin();
    			it2 = (*it1).erase(it2, it2+oldValue.size());
    			(*it1).insert(it2, newValue.begin(), newValue.end());
    		}
    		else
    		{
    			string::iterator it3 = (*it1).begin();
    			string::iterator it4 = oldValue.begin();
    			while (it3 != (*it1).end())
    			{
    				if ((*it3) == (*it4))
    				{
    					string sub = (*it1).substr(it3-(*it1).begin(), oldValue.size());
    					if (sub == newValue)
    					{
    						unsigned offset = it3 - (*it1).begin();
    						it3 = (*it1).erase(it3, it3+oldValue.size());
    						(*it1).insert(it3, newValue.begin(), newValue.end());
    						it3 = (*it1).begin() + offset + newValue.size() - 1;
    					}
    				}
    				it3++;
    			}
    		}
    		it1++;
    	}
    
    	for (auto i = vec.begin(); i != vec.end(); i++)
    		cout << *i << endl;
    
    }
    
    int main()
    {
    	//略
    
    	return 0;
    }
    

      

  • 相关阅读:
    JSP标准标签库(JSTL)--JSTL简介与安装
    JSP标签编程--简单标签
    Tomcat数据源
    Linux 更新vim
    perl 函数
    js 使用a标签 下载资源
    js arrayBuffer 字节序问题,小端法,大端法
    js 的 ArrayBuffer 和 dataView
    ajax 获取服务器返回的XML字符串
    遍历form表单里面的表单元素,取其value
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5874278.html
Copyright © 2011-2022 走看看