025 替換字符串中的空格(keep it up)

劍指offer中題目:http://ac.jobdu.com/problem.php?pid=1510

題目描述:

請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。

輸入:

每個輸入文件僅包含一組測試樣例。
對於每組測試案例,輸入一行代表要處理的字符串。

輸出:

對應每個測試案例,出經過處理後的字符串。

樣例輸入:
We Are Happy
樣例輸出:
We%20Are%20Happy
這個題用c++std::string做的,不過用c也能做,可能麻煩,但是速度快。

代碼:

#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
    std::string ReStr = "%20";
    std::string InputStr;
 
    getline(std::cin, InputStr);
 
    size_t Pos = 0;
    while (true)
    {
        Pos = InputStr.find(' ', Pos);
        if (Pos == std::string::npos) 
        {
            break;
        }
 
        std::string::iterator It = InputStr.begin() + Pos;
        InputStr.replace(It, It+1, ReStr.begin(), ReStr.end());
        Pos += ReStr.size();
    }
 
    std::cout << InputStr << std::endl;
 
    //system("pause");
 
    return 0;
}
/**************************************************************
    Problem: 1510
    User:
    Language: C++
    Result: Accepted
    Time:870 ms
    Memory:2284 kb
****************************************************************/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章