function replaceSpace(str)
{
var temp = '';
for(var i=0;i<str.length;i++){
if (str[i] == " ")
temp += "%20";
else
temp += str[i];
}
return temp;
}
或者正则表达式做法:
function replaceSpace(str)
{
return str.replace(/\s/g,"%20");
}
扩展题:
两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2,实现一个函数:把A2中的所有数字插入到A1中并且所有的数字是排序的。
function merge(arr1,arr2){
var len1=arr1.length-1;
var len2=arr2.length-1;
var len=len1+len2+1;
var arr=new Array();
while(len1>=0&&len2>=0){
if(arr1[len1]<=arr2[len2]){
arr[len]=arr2[len2];
len--;
len2--;
}else{
arr[len--]=arr1[len1--];
}
}
while(len1>=0){
arr[len--]=arr1[len1--];
}
while(len2>=0){
arr[len--]=arr2[len2--];
}
return arr;
}
//运行结果:
merge([1,2,3,4,5],[2,4,6,7,7,8,10]);
[1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 8, 10]
C++写法:
#include <iostream>
using namespace std;
void merge(int a[],int len1,int b[],int len2)
{
int i = len1+len2;
i--;
len1--;
len2--;
while(len1 >= 0 && len2 >= 0)
{
if (a[len1] >= b[len2])
{
a[i--] = a[len1--];
}
else
{
a[i--] = b[len2--];
}
}
while (len1 >= 0)
{
a[i--] = a[len1--];
}
while (len2 >= 0)
{
a[i--] = b[len2--];
}
}
int main(){
int a[5] = { 1, 3, 5, 7, 8 };
int b[3] = { 2, 5, 7 };
merge(a, 5, b, 3);
std::cout << "[";
for (int index = 0; index <8;index++)
{
std::cout << a[index];
if(index!=7)
{
std::cout << ",";
}
}
std::cout << "]";
}