剑指offer-刷题笔记-简单题-JZ5 替换空格
版本1
不知道可以通过索引直接从string s中访问元素,建立了一个char 型数组过渡
class Solution {
public:
string replaceSpace(string s) {
string result;
char char_s[1000];
sprintf(char_s,s.c_str());
int j = 0;
while (char_s[j] != '\0')
{
if (char_s[j]==' ')
{
result+= "%20";
}else{
result+= char_s[j];
}
j++;
}
return result;
}
};
版本2
直接使用string s 索引访问元素,判断元素
class Solution {
public:
string replaceSpace(string s) {
string result;
int j = 0;
while (s[j] != '\0')
{
if (s[j]==' ')
{
result+= "%20";
}else{
result+= s[j];
}
j++;
}
return result;
}
};