Sword refers to Offer——string (two): replace spaces

Please implement a function to replace every space in a string with "%20". For example, when the string is We Are Happy. The replaced string is We%20Are%20Happy.

Idea: The string type is converted to a char array, and the += method is used for splicing.

import java.util.*;


public class Solution {
    
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceSpace (String s){
    
    
        //string类型转化为char数组,+=的方式进行拼接。
        String a="";
        char[] chars = s.toCharArray();
        for(int i=0;i<chars.length;i++)
        {
    
    
            if(chars[i]==' '){
    
    
                a+="%20";
            }else{
    
    
                a+=chars[i];
            }
        }
        return a;
        
    }
}

Guess you like

Origin blog.csdn.net/QXANQ/article/details/115164171