空格替换

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。

给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。

测试样例:
"Mr John Smith”,13
返回:"Mr%20John%20Smith"
 
”Hello  World”,12
返回:”Hello%20%20World”

解题:利用string类的replace成员函数
    
   replace(found,b.size(),c);//从下标found开始替换的长度为b.size(),用c进行替换
   如果要替换一个字符串的的全部某个单词通常配合find函数进行使用,find函数返回查找单词的下标

代码如下:
class Replacement {
public:
    string replaceSpace(string iniString, int length) {
        
        // write code here
        int found= iniString.find(" ");
        while(found!=-1)
        {
            
         iniString.replace(found,1,"%20");
         found= iniString.find(" ",found+1);    
        } 
        return iniString;
        
    }
};

  还有一种形式就是给出的参数是char *类型的,如果还要用string类的replace成员函数就要进行强制转换或者赋值

  请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

代码如下:

class Solution {
public:
    void replaceSpace(char *str,int length) {
        string s="";
        for(int i=0;i<length;i++){
            s+=str[i];
        }
        int found= s.find(" ");
        while(found!=-1)
        {
             
         s.replace(found,1,"%20");
         found= s.find(" ",found+1);   
        }
        for(int i=0;i<s.size();i++){
            str[i]=s[i];
        }str[s.size()]='';
    
    }
};

 java版本

class Solution {
    public String replaceSpace(String s) {
    int len = s.length();    
    char []str =new char[3*len];
    int top = 0;
    for(int i=0;i<len;i++){
       char ch = s.charAt(i);
        if(ch == ' '){
         str[top++]='%';
         str[top++]='2';
         str[top++]='0';
        }else{
            str[top++]=ch;
        }
    }
    return new String(str,0,top); 
    }
}

  

不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/11130721.html