替换空格

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


package SwordOffer;

/** * @author jinhuajian * @data 2018年12月27日---上午9:58:25 * @blog https://me.csdn.net/qq_37119939 */
public class Solution_02 {
	public String replaceSpace(StringBuffer str) {
		if (str == null || str.length() < 1) {
			return "";
		}
		int n = str.length();
		String s = str.toString();
		return s.replaceAll(" ", "%").replace(".", "。");
	}

	// StringBuffer是线程安全的,方法用synchronized的方法修饰
	// StringBuilder线程不安全
	public String replaceSpace_1(StringBuffer str) {
		if (str == null || str.length() == 0) {
			return "";
		}
		for (int i = 0; i != str.length(); i++) {
			if (str.charAt(i) == ' ') {
				str.replace(i, i + 1, "%20");
			}
		}
		return str.toString();
	}

	public static void main(String[] args) {
		Solution_02 s2 = new Solution_02();
		StringBuffer str = new StringBuffer("We are family.");
		String s = s2.replaceSpace(str);

		System.out.println(s);

	}
}

Python版

class Solution:
    # s 源字符串
    def replaceSpace(self, str):
        # write code here
            length = len(str)
        if length == 0:
            return
        count = 0
        for i in range(length):
            if str[i] == ' ':
                count += 1
        neLength = length + count * 2
        newStr = [0]*neLength
        newLength =neLength- 1
        for i in range(length-1,-1,-1):
            if str[i] != ' ':
                newStr[newLength] = str[i]
                newLength -= 1
            else:
                newStr[newLength] = '0'
                newLength -= 1
                newStr[newLength] = '2'
                newLength -= 1
                newStr[newLength] = '%'
                newLength -= 1
        #将字符串数组拼接成字符串
        Str = ''
        for i in range(neLength):
            Str = Str + newStr[i]
        return Str```

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务