Prove safety offer two: string replaces the space

Title Description 

  Please implement a function, a string to replace each space to "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.

 

My thoughts:

package com.jianzhioffer;

public class ReplaceSpace {
	public static void main(String[] args){
		StringBuffer str = new StringBuffer("We Are Happy");
		
		System.out.println(ReplaceSpace.replaceSpace(str));
	}
	
	public static String replaceSpace(StringBuffer str) {
		StringBuffer newStr = new StringBuffer();
		for(int i=0; i<str.length(); i++){
			char ch = str.charAt(i);
			if(str.charAt(i) == ' '){
				newStr.append("%20");
			}else{
				newStr.append(ch);
			}
			
			
		}
		return newStr.toString();
    }
}

 

 

This question is very simple, basically what the algorithm is not used. . .

Guess you like

Origin blog.csdn.net/m0_37564426/article/details/91492219