空格替换 牛客网 程序员面试金典 C++ Python

mac2022-06-30  87

空格替换 牛客网 程序员面试金典 C++ Python

题目描述

请编写一个方法,将字符串中的空格全部替换为“ ”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。

给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。

测试样例:

"Mr John Smith”,13

返回:"Mr John Smith"

”Hello World”,12

返回:”Hello World”

C++

class Replacement { public: //run:3ms memory:480k string replaceSpace(string iniString, int length){ string tmp; for (auto begin = iniString.begin(); begin != iniString.end(); ++begin){ if(*begin == ' ') tmp +=" "; else tmp.push_back(*begin); } return tmp; } };

Python

class Replacement: #run:23ms memory:5732k def replaceSpace(self, iniString, length): iniString = iniString.replace(" ", " ") return iniString

 

转载于:https://www.cnblogs.com/vercont/p/10210307.html

最新回复(0)