02 替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

 

 1 import java.util.*;
 2 public class Solution {
 3     public static String replaceSpace(StringBuffer str) {
 4         if (str == null)
 5             return null;
 6         StringBuffer temp = new StringBuffer();
 7         for(int i=0; i< str.length(); i++){
 8             if(str.charAt(i) == ' '){
 9                 temp.append("%20");
10             }else{
11                 temp.append(str.charAt(i));
12             }
13         }
14         return temp.toString();
15     }
16     public static void main(String[] args){
17         Scanner sc = new Scanner(System.in);
18         System.out.println("请输入要替换的字符串:");
19         StringBuffer str = new StringBuffer();
20         str.append( sc.next());
21         String result = replaceSpace(str);
22         System.out.println("替换后的字符串为:"+ result);
23     }
24 }

 

posted @ 2019-06-27 09:45  淡如水94  阅读(108)  评论(0)    收藏  举报