题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
实现语言:Java
public class Solution { public String replaceSpace(StringBuffer str) { char[] sc=str.toString().toCharArray(); int replaceLen=0; for(int i=0;i<sc.length;++i){ if(sc[i]==' '){ ++replaceLen; } } char[] res=new char[sc.length+2*replaceLen]; int oldLen=sc.length-1; int newLen=res.length-1; while(newLen>=0){ if(sc[oldLen]==' '){ res[newLen--]='0'; res[newLen--]='2'; res[newLen--]='%'; }else{ res[newLen--]=sc[oldLen]; } --oldLen; } return String.valueOf(res); } }
实现语言:Java
public class Solution { public String replaceSpace(StringBuffer str) { StringBuffer sb=new StringBuffer(); char[] sc=str.toString().toCharArray(); for(int i=0;i<sc.length;++i){ if(sc[i]==' '){ sb.append("%20"); }else{ sb.append(sc[i]); } } return sb.toString(); } }
实现语言:python
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here l=list(s) r=['%20' if ss==' ' else ss for ss in l] return ''.join(r)