【5】Replace all spaces in a string with ‘%20’

时间:2022-05-17 16:48:21

Question:Write a method to replace all spaces in a string with ‘%20’. 

package CareerCup;

public class ReplaceSpace 
{
	public ReplaceSpace(){}
	public String replace(String str)
	{
		String strReplaced = "";
		for(int i=0;i<str.length();i++)
		{
			if(str.charAt(i)==' ') strReplaced +="20%";
			else strReplaced+=str.charAt(i);
		}
		return strReplaced;
	}
	public static void main(String[] args)
	{
		String str = "ab c de gj";
		ReplaceSpace rs = new ReplaceSpace();
		String strReplaced = rs.replace(str);
		System.out.println("The orignal string:"+str);
		System.out.println("The replaced string:"+strReplaced);
	}
}