[Jianzhi Offer] 05, replace the space in the character creation; Difficulty level: easy.
Article Directory
1. Topic
2. Topic background
In network programming, if URL parameters contain special characters, such as spaces, #, etc., the server may not be able to obtain correct parameter values. We need to convert these special symbols into characters that the server can recognize.
The conversion rule is followed by % followed by the two-digit hexadecimal representation of the ASCII code, for example:
空格 的ASCI码是32,即十六进制的0x20,因此空格被替换成"%20"
'#'的ASCII码为35,即十六进制的0x23,它在URI中被替换为"%23"。
3. My answer
Basic answer:
class Solution {
public:
string replaceSpace(string s) {
string s_new;
for(auto a:s){
if(a==' ')
s_new+="%20";
else
s_new+=a;
}
return s_new;
}
};
Advanced syntax (replacing if - else statements with the ternary operator)
class Solution {
public:
string replaceSpace(string s) {
string s_new;
for(auto iter:s){
string iter_str(1,iter);
s_new+=(iter==' ') ? "%20":iter_str;
}
return s_new;
}
};
Results of the:
执行用时:0 ms, 在所有 C++ 提交中击败了 100.00% 的用户
内存消耗:6 MB, 在所有 C++ 提交中击败了 81.92% 的用户
Four, error-prone
In the advanced grammar, directly writing the following format will compile and report an error:
class Solution {
public:
string replaceSpace(string s) {
string s_new;
for(auto iter:s)
s_new+=(iter==' ') ? "%20":iter;
return s_new;
}
};
The main idea of the error is that "%20" is of string type, while iter is of char type, and the two are inconsistent. Therefore, iter needs to be converted to string type.
5. Knowledge point: conversion of char and string types
It is wrong to use string(iter) directly, because the string class does not have a constructor like string( char c). The correct constructor is:
string(size_t n, char c); // 使用 n 个字符 'c' 初始化string对象
So we use string iter_str (1, iter) to convert char type iter to string type iter_str
There are several other ways to convert char to string, please refer to the blog several ways to convert char to string in c++