String: replace spaces

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.

Problem-solving ideas

New StringBuffer (), is inserted from the rear forward traversal;

Reference Code

 1 public class Solution {
 2     public String replaceSpace(StringBuffer str) {
 3         StringBuffer s = new StringBuffer();
 4         for(int i = str.length() - 1; i >= 0; i--) {
 5             if(str.charAt(i) == ' ') {
 6                 s.append("02%");
 7             } else {
 8                 s.append(str.charAt(i));
 9             }
10         }
11         return s.reverse().toString();
12     }
13 }

 

Guess you like

Origin www.cnblogs.com/carry6/p/11519487.html