【Python】剑指offer-面试题5:替换空格

题目描述

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

# -*- coding:utf-8 -*-
# 这道题对于Python来说似乎没有意义
# 在Python中字符串类型是不可变类型,即不可以在原处修改
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        s = s.replace(' ', '%20')
        return s
if __name__=='__main__':
    s = Solution()
    string = "we are happy"
    print(s.replaceSpace(string))
# 这道题对于Python来说似乎没有意义
# 在Python中字符串类型是不可变类型,即不可以在原处修改

贴一段C++的代码:

#include <iostream>
#include <String.h>
using namespace std;

class Solution {
public:
	void replaceSpace(char *str,int length) {
		int spaceNum=0;
         //得出原字符串中空格的数量 
        for(int i=0;i<length;i++)
        {
            if(str[i]==' ')
                spaceNum++;
             
        }    
        //计算出替换空格后的字符长度 
        int newIndex=length+2*spaceNum;
        char *index=str+length;
        //从后往前替换 
        while(index>=str)
        {
            if(*index==' ')
            {
                str[newIndex--]='0';
                str[newIndex--]='2';
                str[newIndex--]='%';
            }
            else{
                str[newIndex--]=*index;
            }
            index--;
        }
	}
	
	
};
int main(){
   
 		char s[] = "we are happy";
		int len = strlen(s);
		cout<<len<<endl;
	    Solution Solu;
	    Solu.replaceSpace(s, len);
		cout<<s<<endl;
   		return 0;
	}

猜你喜欢

转载自blog.csdn.net/hushaoqiqimingxing/article/details/89599586