欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

替换空格(python/c++)

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        i=0
        n=len(s)
        ss=[]##初始化定义算法的中间变量
        for i in range(n):
            if s[i].isspace():
                ss.append('%20')#判断为空的时候加入非空的时候不加入
            else:
                ss.append(s[i])
            i+=1
        ss=''.join(ss)##把所有的都连在一起来
        return ss

  

c++代码

#include<iostream>
using namespace std;
class Solution {
public:
	void replaceSpace(char *str, int length) {
		if (str == nullptr || length<0)
			return;
		int count = 0, i = 0;
		while (str[i] != '\0')
		{
			if (str[i] == ' ')
			{
				count++;
			}
			i++;
		}
		int oldlen = i;
		int newlen = i + count * 2;
		if (newlen>length)
			return;
		while (oldlen != newlen)
		{
			if (str[oldlen] != ' ') {
				str[newlen--] = str[oldlen];
			}
			else {
				str[newlen--] = '0';
				str[newlen--] = '2';
				str[newlen--] = '%';
			}
			oldlen--;
		}
		return;
	}

};
int main(){
	const int length = 100;
	char str[length] = "We Are Happy";
	Solution().replaceSpace(str, length);
	cout << str << endl;
	system("pause");
	return 0;
}

  

posted on 2019-02-25 15:30  IT嘟嘟  阅读(149)  评论(0编辑  收藏  举报

导航