空格替换

题目描述

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

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

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


 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         
 5         String s="We Are Happy";
 6         System.out.print(replaceSpace(s,s.length()));
 7     }
 8     /*
 9     public static String replaceSpace(StringBuffer str) {
10     //    String s=null;
11         //StringBuffer tmp=null;
12         int index=str.indexOf(" ");
13         while(index!=-1)
14         {
15             //tmp.append(str.substring(0, str.indexOf(" ")));
16             str.replace(index, index+1, "%20");
17             index=str.indexOf(" ");
18         }
19         return str.toString();
20     }
21 
22     */
23     public static String replaceSpace(String iniString, int length) {
24         // write code here
25         //iniString.replaceAll(" ", "%20");
26         StringBuffer str=new StringBuffer(iniString);
27         
28         int index=str.indexOf(" ");
29         while(index!=-1)
30         {
31             //tmp.append(str.substring(0, str.indexOf(" ")));
32             str.replace(index, index+1, "%20");
33             index=str.indexOf(" ");
34         }
35         return str.toString();
36     }
37 }

 

posted @ 2015-07-06 18:21  小牛的成长  阅读(174)  评论(0编辑  收藏  举报