面试题05:替换空格(C++)

题目描述

面试题05:替换空格链接地址 https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

输入:s = "We are happy."

输出:"We%20are%20happy."

问题分析

step1:遍历字符串,查找空字符

step2:替换空字符为"%20"

编写程序

方法1

 1 class Solution {
 2 public:
 3     string replaceSpace(string s) {
 4      if(s.size() < 1) return s;
 5         string str;
 6         for(auto c : s){
 7             if(c == ' ')
 8                 str += "%20";
 9             else
10                 str += c;
11         }
12         return str;
13     }
14 };
View Code
 

猜你喜欢

转载自www.cnblogs.com/wzw0625/p/12500212.html