careercup-数组和字符串1.4

1.4 编写一个方法,将字符串中的空格全部替换为“%20“。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的”真实“长度。

C++实现代码:

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

string replacespace(string str)
{
    if(str.empty())
        return "";
    int i;
    int len=str.length();
    string res;
    for(i=0;i<len;i++)
    {
        if(isspace(str[i]))
            res+="%20";
        else
            res+=str[i];
    }
    return res;
}

int main()
{
    string str="We are Happy";
    cout<<replacespace(str)<<endl;
}

 

posted @ 2014-12-03 16:23  Jessica程序猿  阅读(99)  评论(0编辑  收藏  举报