1. 程式人生 > 實用技巧 >2、替換空格

2、替換空格

請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

============Python============

# -*- coding:utf-8 -*-
class Solution:
    # s 源字串
    def replaceSpace(self, s):
        # write code here
        res = s.split(' ');
        ans = '';
        for i in range(len(res) - 1):
            ans 
+= res[i] ans += '%20' ans += res[-1] return ans

================Java==============

public class Solution {
    public String replaceSpace(StringBuffer str) {
        //遍歷一遍字串找出空格的數量
        if (str == null || str.length() < 0) {
            return null;
        }
        int spacenum 
= 0; //計算空格數 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') spacenum++; } int indexold = str.length() - 1; int newlength = str.length() + spacenum * 2; int indexnew = newlength - 1; str.setLength(newlength);
for (;indexold>=0 && indexold<newlength; --indexold) { if (str.charAt(indexold) == ' '){ str.setCharAt(indexnew--, '0'); str.setCharAt(indexnew--, '2'); str.setCharAt(indexnew--, '%'); } else { str.setCharAt(indexnew--, str.charAt(indexold)); } } return str.toString(); } }