在c++中将字符串中的空格替换为%20

Replacing spaces in a string by %20 in C++

本文关键字:替换 空格 字符串 c++      更新时间:2023-10-16
#include <iostream>
#include <string>
void removeSpaces(std::string );
int main()
{
        std::string inputString;
        std::cout<<"Enter the string:"<<std::endl;
        std::cin>>inputString;
        removeSpaces(inputString);
        return 0;
}

void removeSpaces(std::string str)
{
        size_t position = 0;
        for ( position = str.find(" "); position != std::string::npos; position = str.find(" ",position) )
        {
                str.replace(position ,1, "%20");
        }
        std::cout<<str<<std::endl;
}

我看不到任何输出。例如

Enter Input String: a b c
Output = a

怎么了?

std::cin>>inputString;

停在第一个空格处。用途:

std::getline(std::cin, inputString);

cin默认止于空格

把你的输入改为:

// will not work, stops on whitespace
//std::cin>>inputString;
// will work now, will read until n
std::getline(std::cin, inputString);

另一种更好的方法是计算空格的数目,创建长度=旧长度+2*count的新字符串,并开始将字符从旧字符串移动到新字符串,除了空格,将其替换为%20....

实施

http://justprogrammng.blogspot.com/2012/06/replace -所有-空间-字符串- - 20. - html