剑指offer【面试题4 : 替换空格】

题目:请实现一个函数,把字符串中的每个空格替换成"%20",
例如“We are happy.”,则输出“We%20are%20happy.”。
思路:
1、遍历string用string temp接收,如果检测到空格就回收子串到vector<string> _str,然后清空temp;
2、遍历_str,给每一个子串加上 "20%"
[题目给的第二个参数没吊用,既然用C++,那就好好用]

 1 //题目:请实现一个函数,把字符串中的每个空格替换成"%20",
 2 //      例如“We are happy.”,则输出“We%20are%20happy.”。
 3 #include<string>
 4 #include<vector>
 5 #include<iostream>
 6 using namespace std;
 7 void replaceSpace(char *str, int length) {
 8     string _string;
 9     _string = str;//将 char* 转换成 string
10     _string += ' '; //我们是一检测到空格 就回收(push_back)该小段字符串,所以确保完整,应该在整个string后面加一个空格
11     // <1> 回收小段字符串
12     vector<string> _str;//收集 tian an men
13     string temp;
14     for (auto& _char:_string)
15     {    
16         if (_char == ' ')//一旦检测到空格就回收子串
17         {
18             _str.push_back(temp);
19             temp="";// 不要写成" "
20         }
21         else
22         {
23             temp += _char;//shi
24         }
25     }
26     // <2>从组操作
27     string shabi = "%20";
28     string result;
29     for (auto&_substr: _str)
30     {
31         string temp = _substr.append(shabi);// +shabi;//每一个子串 + "%20"
32         result += temp;//子串累加
33         cout << "Temp = " << temp.c_str() << endl;
34     }
35     string result_(result.begin(), result.end()-3);// 因为多加了一个,所以删除结果 " % 20"
36     cout << result_.c_str() << endl;
37     //请注意 string 与 char* 的相互转换
38     // https://zhidao.baidu.com/question/1382412488844707980.html
39 
40 }
41 int main()
42 {
43     char* chars = "tian an men";
44     replaceSpace(chars, 8);
45     char* chars_ = "We Are Happy";
46     replaceSpace(chars_, 8);
47     char* chars__ = "hehehehehe";
48     replaceSpace(chars__, 8);
49     return 1;
50 }

原文地址:https://www.cnblogs.com/winslam/p/9457777.html