方法1:API
/**
* @param {string} s
* @return {string}
*/
var replaceSpace = function(s) {
let cur = s.split(' ').join('%20');
// console.log(cur);
return cur;
};
方法2:遍历
/**
* @param {string} s
* @return {string}
*/
var replaceSpace = function(s) {
let newS = '';
for(let item of s) {
if(item == ' '){
newS += '%20';
} else {
newS += item;
}
}
return newS;
};
方法3:尾部扩充
var replaceSpace = function(s) {
let current = Array.from(s);
let oLength = Array.from(s).length;
let count = 0;
for(let i of current) {
if(i == ' ') {
count++;
}
}
let nlength = oLength + count*2;
console.log(nlength,oLength)
let array = new Array(nlength)
for(let i = array.length - 1,j = oLength - 1; j >=0; i--,j--) {
if(s[j] != ' ') {
array[i] = s[j];
} else {
array[i] = '0';
array[i - 1] = '2';
array[i - 2] = '%';
i -= 2;
}
}
return array.join('');
}