面试金典 字符串

 

题目描述

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。

给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。

测试样例:

“Mr John Smith” 13
返回:“Mr%20John%20Smith”
 
“Hello  World”,12
返回:“Hello%20%20World”
 
C++风格解法
法一: 用 string::iterater it 遍历整个字符串,再通过 (*it) 把 ' ' 换成 '%20'
法二: 用 string::find() 查找字符串中的 ' ',再用 string::replace() 把 ' ' 换成 '%20'
 
#include <fstream>
#include <iostream>
using namespace std;

class Replacement_by_iterator {	//法一:AC 
public:
    string replaceSpace(string iniString, int length) 
    {
    	if(length<=0)
    		return 0;
    	string strNew;
    	string::iterator it;
    	for(it=iniString.begin(); it<=iniString.end(); it++)
        {
    	    if(*it==' ')	//注单引号:指向的是单个字符 
               strNew += "%20";
	        else
			   strNew += (*it); 
        }
	    return strNew;
    }
};

class Replacement_by_replace {	//法二:AC
public:
    string replaceSpace(string iniString, int length)     
    {
        string strNew = iniString;
        while(strNew.find(" ") != std::string::npos)	        
        { //npos: string 类将 npos 定义为保证大于任何有效下标的值。即 string类可容纳的最大大小 
             strNew.replace(strNew.find(" "),1, "%20");  
        }
        return strNew;
    }
};

int main(int argc, char** argv) 
{
	ifstream fin("test.txt", ios::in);
	if(fin.fail())
	{
		cout << "文件打开失败" << endl;
		exit(-1);	
	}	
	char ch;
	string testString;
	while(fin.get(ch))
	{
		testString += ch;
	}
	fin.close();
	
	Replacement_by_iterator replace1;  //法一
	Replacement_by_replace replace2;   //法二
	cout << replace1.replaceSpace(testString, testString.length()) << endl;
    cout << replace2.replaceSpace(testString, testString.length());	
        return 0;
}
原文地址:https://www.cnblogs.com/claremore/p/4716016.html