一、题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
二、解题代码
1、python
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
a_str = s
result=""
for char in a_str:
if(char==' '):
result+="%20"
else:
result+=char
return result
2、java
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replaceAll("\\s", "%20");
}
}
3、C#
class Solution
{
public string replaceSpace(string str)
{
return str.Replace(" ", "%20");
}
}
4、PHP
<?php
function replaceSpace($str)
{
return str_replace(" ","%20",$str);
}
5、JavaScript
function replaceSpace(str)
{
return str.replace(/\s/g, "%20");
}