劍指offer中題目:http://ac.jobdu.com/problem.php?pid=1510
- 題目描述:
-
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
- 輸入:
-
每個輸入文件僅包含一組測試樣例。
對於每組測試案例,輸入一行代表要處理的字符串。
- 輸出:
-
對應每個測試案例,出經過處理後的字符串。
- 樣例輸入:
-
We Are Happy
- 樣例輸出:
-
We%20Are%20Happy
代碼:
#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
****************************************************************/