首页 > 试题广场 >

替换空格

[编程题]替换空格
  • 热度指数:1678734 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
查找,然后连接,然后删除
发表于 2017-03-29 10:05:04 回复(0)
更多回答
推荐
//思路
//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)

思路:从前向后记录‘ ’数目,从后向前替换‘ ’。 重点:从后向前替换的时候的技巧 例如:“we are lucky”

0 1 2 3 4 5 6 7 8 9 10 11
w e a r e l u c k y

可以得知count=2;//空格的个数。 所以在替换的时候7~11的字母要向后移动count×2个位置,3~5字母要向后移动(count-1)×2个位置。 所以得到 :

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e   a r e   l u c  k y 
w e   a r a r e u c  k l u c k y

在替换的时候直接在空格处写入%20了

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e   a r e   l u c  k y 
w e % 2 0 a r e % 2  0 l u c k y
class Solution {
public:
    void replaceSpace(char *str,int length) {
        int count=0;
        for(int i=0;i<length;i++){
            if(str[i]==' ')
                count++;
        }
        for(int i=length-1;i>=0;i--){
            if(str[i]!=' '){
                str[i+2*count]=str[i];
            }
            else{
                count--;
                str[i+2*count]='%';
                str[i+2*count+1]='2';
                str[i+2*count+2]='0';
            }
        }
    }
};
发表于 2017-04-14 11:44:26 回复(78)
用的java
public class Solution {
    public String replaceSpace(StringBuffer str) {
        StringBuffer out=new StringBuffer();
        for (int i = 0; i < str.toString().length(); i++) {
            char b=str.charAt(i);
            if(String.valueOf(b).equals(" ")){
                out.append("%20");
            }else{
                out.append(b);
            }
        }
        return out.toString();  	
    }
}

发表于 2015-09-22 11:57:46 回复(12)
public class Solution {
    public String replaceSpace(StringBuffer str) {
        String sti = str.toString();
    	char[] strChar = sti.toCharArray();
        StringBuffer stb = new StringBuffer();
        for(int i=0;i<strChar.length;i++){
            if(strChar[i]==' '){
                stb.append("%20");
            }else{
                stb.append(strChar[i]);
            }
        }
        return stb.toString();
    }
}

发表于 2015-08-25 19:53:36 回复(31)
分析:先转为string,然后处理完成后再转为char *。但不是以返回值的形式,还要利用好原来的空间,用strcpy实现之。处理过程循环查找,每次找到就替换,且把每次的找到的结果当成下一次的参数,避免重复从头查找。

class Solution {
public:
	void replaceSpace(char *str,int length) {
        string s(str);
        int i=0;
		while((i=s.find(' ',i))>-1){
			s.erase(i,1);
            s.insert(i,"%20");
            
        }
        auto ret=s.c_str();
        strcpy(str,ret);
	}
};

发表于 2017-08-20 03:18:51 回复(14)
RX头像 RX
public class Solution {
    public String replaceSpace(StringBuffer str) {
    	return str.toString().replaceAll("\\s", "%20");
    }
}

发表于 2015-10-28 17:56:38 回复(61)
不知道能不能用Python,反正很方便

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        return "%20".join(list(s.split(" ")))
        
发表于 2018-04-03 11:24:24 回复(9)
题目考查的肯定不是用replace函数啦~
思路是:从左到右遍历,从右到左替换。

class Solution {
public:
void replaceSpace(char *str,int length) {
for(int i = 0; i < length; i ++){
            if(*(str+i) == ' '){
                length += 2;
                int j = length -1;
                while(j-2 > i){
                    *(str+j) = *(str+j-2);
                    j--;
                }
                *(str+i) = '%';
                *(str+i+1) = '2';
                *(str+i+2) = '0';
            }
        }
}
};

发表于 2015-08-31 22:13:12 回复(19)
第二遍自己做发现了更简单的办法哟~
public class Solution {
    public String replaceSpace(StringBuffer str) {
        String s = str.toString();
        if(str==null)
            return s;
         char []ss=s.toCharArray();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<ss.length;i++)
            {
            if(ss[i]==' ')
                {
                 sb.append("%20");
            }
           else 
               sb.append(ss[i]);
        }
        return sb.toString();
    }
}

发表于 2017-06-23 17:08:34 回复(9)
Java 一行搞定啊
public class Solution {
    public String replaceSpace(StringBuffer str) {
     return str.toString().replaceAll(" " , "%20");
    }
}

JavaScript
function replaceSpace(str)
{
    var resStr = str.replace(/ /g, "%20");
    return resStr;
}
发表于 2017-09-04 10:52:56 回复(8)
class Solution {
public:
	void replaceSpace(char *str,int length) {
		int spaceNum=0;
        
        for(int i=0;i<length;i++)
        {
            if(str[i]==' ')
                spaceNum++;
            
        }     
        
        int newIndex=length+2*spaceNum;
        char *index=str+length;
		while(index>=str)
        {
            if(*index==' ')
            {
                str[newIndex--]='0';
                str[newIndex--]='2';
                str[newIndex--]='%';
            }
            else{
                str[newIndex--]=*index;
            }
            index--;
        }
    }
};

发表于 2015-09-27 00:11:08 回复(12)
//JAVA的同学看这里。我用JAVA按照C++的思路写了一份,原理和思路,我这里用了输出语句展示替换过程。其他老哥已经讲得很清楚了 
牛客网代码编辑太麻烦:

发表于 2018-11-02 08:27:57 回复(1)

很简单啊,有漏洞吗

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        new_s = ''
        for j in s:
            if j == ' ':
                new_s=new_s + '%20'
            else:
                new_s=new_s + j
        return new_s
发表于 2018-03-05 22:55:37 回复(12)
class Solution {
public:
 void replaceSpace(char *str,int length)
    {
 int count=0;
        for(int i=0;i<length;i++)
        {
            if(str[i]==' ')
                count++;
        }
        int newLength=length+2*count;

        for(int i=length-1;i>=0;i--)
        {
            if(str[i]!=' ')
            {
                str[i+2*count]=str[i];
            }
            else
            {
                str[i+2*count]='0';
                str[i+2*count-1]='2';
                str[i+2*count-2]='%';
                count--;
            }
        }
 }
};

发表于 2015-04-06 16:18:26 回复(0)
public class Solution {
    public String replaceSpace(StringBuffer str) {
        StringBuffer st = new StringBuffer();
        for(int i = 0; i < str.length() ; i++){
            char s = str.charAt(i);
            if(String.valueOf(s).equals(" ")){
                st.append("%20");
            }
            else{
                st.append(s);
            }
        }
        return st.toString();
    }
}

发表于 2018-07-07 19:54:53 回复(0)
js自带函数。
function(str){
    return encodeURI(str);
}
发表于 2018-05-07 19:10:22 回复(1)
public  String replaceSpace(StringBuffer str) {
        
        return str.toString().replaceAll("\\s","%20");
}

使用正则表达式替换

发表于 2017-03-17 12:56:06 回复(5)
# -*- coding:utf-8-*-
classSolution:
    # s 源字符串
    def replaceSpace(self, s):
       return s.replace(' ','%20')
发表于 2016-01-31 12:00:09 回复(5)
弄个队列先把字符串进队,依次出队,遇到空格连接%20字符串,继续出队
发表于 2016-03-29 15:14:25 回复(5)
package alex.suda.jzOffer;

import java.util.Scanner;

public class ReplaceSpace {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			String s = scanner.nextLine();
			StringBuffer str = new StringBuffer(s);
			System.out.println(replaceSpace(str));
		}
	}

	public static String replaceSpace(StringBuffer str) {
		if (str == null) {
			return null;
		}
		int blankNum = 0;
		int length = str.length();
		int newLength = 0;
		for (int i = 0; i < length; i++) {
			if (str.charAt(i) == ' ') {
				blankNum++;
			}
		}
		newLength = length + 2 * blankNum;//替换后的字符串长度
		char[] newChars = new char[newLength];//新的字符数组
		int index = newLength - 1;
		for(int i=length-1;i>=0;i--) {
			if (str.charAt(i) == ' ') {
				newChars[index--] = '0';
				newChars[index--] = '2';
				newChars[index--] = '%';
			} else {
				newChars[index--] = str.charAt(i);	
			}
		}
		return new String(newChars);
	}
}


发表于 2016-11-16 16:54:07 回复(1)
package HuaWei;
public class Replace {
 /**
 * 请实现一个函数,将一个字符串中的空格替换成“%20”。
 * 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 */
 public static void main(String[] args) {
 String s = "We Are Happy";
 re(s);
 }
 public static void  re(String s ){
 String[] all = s.split(" ");
 StringBuffer sb =  new StringBuffer();
 StringBuffer sb1 = new StringBuffer();
 for(int i = 0;i<all.length;i++){ 
 if(i!=all.length-1){
 sb1.append(all[i]+"%20");
 }
 else
 sb1.append(all[i]);
 }
 System.out.println(sb.append(sb1));
 }
}

发表于 2015-04-08 22:03:43 回复(0)