首页 > 试题广场 >

替换空格

[编程题]替换空格
  • 热度指数:1678765 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
推荐
//思路
//1:从前往后插入,这样移动·的次数多不建议
//2:从后往前插入

class Solution {
public:
void replaceSpace(char *str,int length) {
        //遍历一边字符串找出空格的数量
        if(str==NULL||length<0)
            return ;
        int i=0;
        int oldnumber=0;//记录以前的长度
        int replacenumber=0;//记录空格的数量
        while(str[i]!='\0')
            {
               oldnumber++;
               if(str[i]==' ')
                   {
                     replacenumber++;
                   }
                  i++; 
            }
        int newlength=oldnumber+replacenumber*2;//插入后的长度
        if(newlength>length)//如果计算后的长度大于总长度就无法插入
            return ;
        int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
        int pNewlength=newlength;
        while(pOldlength>=0&&pNewlength>pOldlength)//放字符
            {
              if(str[pOldlength]==' ') //碰到空格就替换
                  {
                     str[pNewlength--]='0';
                     str[pNewlength--]='2';
                     str[pNewlength--]='%';
                     
                  }
               else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
               {
                    str[pNewlength--]=str[pOldlength];
                   
               }
             pOldlength--; //不管是if还是elsr都要把pOldlength前移
             
           }
        

}
};
编辑于 2015-12-07 18:51:44 回复(308)
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s=s.replace(' ','%20')
        return s


发表于 2020-11-29 14:08:15 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        line = s.split(" ")
        return "%20".join(line)

发表于 2020-11-24 12:56:01 回复(0)
def func(s):
    new_str = ''
    for ch in s:
        if ch != ' ':
            new_str += ch
        else:
            new_str += '%20'
    return new_str

创建一个新的空字符串,然后遍历旧字符串,不等于空格的字符串直接拼接到新字符串上,等于空格的部分用'%20'拼接,然后返回新字符串new_str

发表于 2020-11-04 21:03:50 回复(0)
class Solution:
    def replaceSpace(self, s):
        l=s.split(' ')
        return '%20'.join(l)
发表于 2020-10-15 22:02:22 回复(0)
法1:
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return(s.replace(' ','%20'))
法2:
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = s.split(' ')
        tube = ''
        for i in s:
            tube += '%20' + i
        return(tube[3:])
法3:
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        n = len(s)
        tube = []
        for i in range(n):
            if s[i] == ' ':
                tube.append('%20')
            else:
                tube.append(s[i])
        return ''.join(tube)




编辑于 2020-10-13 01:06:09 回复(0)

普通思路:
构建辅助字符串
只要啊==' '
则加入'%20'

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        if s == None:
            return None
        n = len(s)
        rep_str = ''
        for i in range(n):
            if s[i] == ' ':
                rep_str += '%'
                rep_str += '2'
                rep_str += '0'
            else:
                rep_str += s[i]
        return rep_str
发表于 2020-09-07 21:53:41 回复(0)
写完类之后,自己写了
abb = Solution()
string = input() print(abb.replaceSpace(string))
然后疯狂报错,说我的输出少一个双引号,也是醉了。
发表于 2020-08-13 16:45:22 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = list(s)
        count = len(s)
        for i in range(count):
            if s[i] == " ":
                s[i] = "%20"
        return "".join(s)

发表于 2020-07-29 15:33:44 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        i = 0
        while(0<=i<len(s)):
            if(s[i]==' '):
                s = list(s)
                s[i]='%20'
                s = ''.join(s)
            i += 1
            
        return s
发表于 2020-06-14 19:35:10 回复(0)
Python Version:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
C++ Version:
class Solution {
public:
	void replaceSpace(char *str,int length) {
        if(str==NULL|length==0) return;
        int lenOldStr = 0;
        int numSpace = 0;
        while(str[lenOldStr]!='\0'){
            if(str[lenOldStr]==' ') numSpace++;
            lenOldStr++;
        }
        int lenNewStr = lenOldStr + 2*numSpace;
        int pNewStr = lenNewStr;
        int pOldStr = lenOldStr;
        while(pOldStr>=0 && pOldStr<pNewStr){
            if(str[pOldStr]==' '){
                str[pNewStr--] = '0';
                str[pNewStr--] = '2';
                str[pNewStr--] = '%';
                pOldStr--;
            }
            else{
                str[pNewStr--] = str[pOldStr--];
            }
        }

	}
};


编辑于 2020-06-01 16:24:09 回复(0)
class Solution:
    def replaceSpace(self, s):
        # write code here
        res = ""
        for i in s:
            if i == " ":
                res += "%20"
            else:
                res += i
        return res

发表于 2020-05-15 14:41:59 回复(0)

大哥们都怎么越过25字评论限制的啊

发表于 2020-04-21 09:06:15 回复(0)
 
使用python s.split()方法,将字符串按空格拆开保存为列表,再用 '%20'.join() 方法将列表中的原素用’20%‘连接。
发表于 2020-04-15 22:53:36 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    (763)# s 源字符串
    def replaceSpace(self, s):
        # write code here
        res=[]
        for i in range(len(s)):
            if s[i]==" ":
                res.append("%20")
            else:
                res.append(s[i])
        res=''.join(res)
        return res

发表于 2020-03-24 14:58:05 回复(0)
菜鸡一枚,不用python中的replace函数,通过数组及字符串拼接方式拟写
class Solution:
    def replaceSpace(self,s):
        if s == "":
            RE=""
            return RE
        else:
            X = list(s)
            i=0
            while i<len(s):
                if X[i] == " ":
                    X[i] = "%20"
                i += 1
            j = 1
            RE = str(X[0])
            while j<len(s):
                RE = str(RE)+str(X[j])
                j += 1
            return RE
发表于 2020-03-23 19:38:50 回复(0)
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        s = s.replace('  ', '%20')
        return s
发表于 2020-03-20 17:26:41 回复(0)

python的实现的方法很简单,s.replace(' ','%20')

发表于 2020-03-11 11:54:40 回复(0)
使用正则表达式,一条语句就搞定了。python处理字符串还是具有得天独厚的优势啊。
import re
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        (2014)# write code here
        return re.sub('\s','%20',s)

发表于 2020-03-10 07:17:58 回复(0)
(python实现)在判断字符串中是否存在空格时,使用方式一老是因为这个问题变成不通过,后来改成方式二编程通过: 方式一:`if ' ' in s:`判断s中是否存在空格 和 方式二:if ' ' == s[i]: 请问有没有人知道这两种方式有什么区别?
发表于 2020-02-26 18:51:31 回复(0)
Python实现,欢迎交流。
def replaceSpace(self, s):
        # write code here
        sList = []
        for c in range(len(s)):
            if s[c] == ' ':
                sList.append('%20')
            else:
                sList.append(s[c])
        s1 = ''.join(sList)
        return s1
发表于 2020-02-26 14:30:51 回复(0)