当前位置:网站首页>Sword finger offer 05 Replace spaces

Sword finger offer 05 Replace spaces

2022-06-22 23:39:00 Front end plasterer

One algorithm a day ~~, Stick to the first day .

Please implement a function , Put the string s Replace each space in with "%20".
Range :0 <= s The length of <= 10000

Example :

	 Input :s = "We are happy."
	 Output :"We%20are%20happy."	

How to solve the problem 1:
Ideas : Simple and rough direct use split Method , Separate them into string arrays with spaces , And then use join Method is then converted to a string .

	function replaceSpace(s){
    
		if(s.length > 10000) return null;
		return s.split(" ").join("%20");
	}

How to solve the problem 2:
Ideas : Replace with regular expressions

	function replaceSpace(s){
    
		if(s.length > 10000) return null;
		return s.replace(/ /g, '%20')
	}

How to solve the problem 3:
Ideas : Loop string , Then determine whether there is a blank space , If there are spaces, replace them with

	function replaceSpace(s){
    
	    if(s.length > 10000) return null;
    	let str = ''
    	for (const key in s) {
    
        	if(s[key] === ' '){
    
            	str = str + '%20'
        	}else{
    
            	str = str + s[key]
        	}
    	}
    	return str;
    }

Now think of these methods . If there is still a good way , I hope you can share more .

Code Not just for young people , It should be a lifelong hobby ~

原网站

版权声明
本文为[Front end plasterer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222051389933.html