请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy." 限制: 0 = s 的长度 = 10000 https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
class Solution {
public:
string replaceSpace(string s) {
int n=s.size();
string res;
for (int i=0;i<n;i++)
{
//注意此时空格是字符' ',不是字符串“ ”
if(s[i]==' ')
res+="%20";
else
res+=s[i];
}
return res;
}
};
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str;
string res;
//获取输入
getline(cin, str);
//将输入给流
stringstream ss(str);
int n = str.size();
for(int i=0;i<n;i++)
{
if (str[i] == ' ')res += "%20";
else res += str[i];
}
cout << res<< endl;
}