LeetCode刷题(159)~替换空格【 replace() 】

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


题目描述

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例 1:

输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

  • 0 <= s 的长度 <= 10000

解答 By 海轰

提交代码

string replaceSpace(string s) {
string ans;
for(char i:s)
{
if(i==' ')
ans+="%20";
else
ans+=i;
}
return ans;
}

运行结果

LeetCode刷题(159)~替换空格【 replace() 】_提交代码


提交代码

string replaceSpace(string s) {
int length = s.length();
while (length >= 0)
{
if (s[length] == ' ')
{
s.replace(length, 1, "%20");
}
length--;
}
return s;
}

运行结果

LeetCode刷题(159)~替换空格【 replace() 】_字符串_02


提交代码

string replaceSpace(string s) {
int n=0;
while(n<s.size())
{
if(s[n]==' ')
s.replace(n,1,"%20");
++n;
}
return s;
}

运行结果

LeetCode刷题(159)~替换空格【 replace() 】_字符串_03

题目来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

“LeetCode刷题(159)~替换空格【 replace() 】” 的相关文章