请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
class Solution {
public:
string replaceSpace(string s) {
string result;
for(auto c:s)
{
if(c==' ')
{
result +="%20";
}
else
result +=c;
}
return result;
}
};
for(auto c:s):表示将容器s中的元素从前往后枚举出来,并用c来表示
for在C++11中的特性用一下的例子说明:
for(auto i:v)
for(auto &i:v)
实例1:
代码1:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto &i : s ) //i是个引用 i到底引用的是什么?
i = toupper(i); //改变成大写,影响s的值
cout<<s<<endl; //s的值是 HELLO
实例2:
代码2:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto i : s ) //书上说i 是char类型,那s[n]呢?
i = toupper(i); //改变成大写,不影响s的值
cout<<s<<endl; //s的值是 hello
它们的区别在于count是值还是引用。