C++ 用下划线替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5252612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:46:05  来源:igfitidea点击:

Replace space with an underscore

c++removing-whitespace

提问by Luke Berry

I am trying to write something that will replace all the spaces in a string with an underscore.

我正在尝试编写一些东西,用下划线替换字符串中的所有空格。

What I have so far.

到目前为止我所拥有的。

string space2underscore(string text)
{
    for(int i = 0; i < text.length(); i++)
    {
        if(text[i] == ' ')
            text[i] = '_';
    }
    return text;
}

For the most part this would work, if I was doing something like.

在大多数情况下,这会起作用,如果我正在做类似的事情。

string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;

That would output "hello_stackoverflow", which is just what I want.

那将输出“hello_stackoverflow”,这正是我想要的。

However if I was to do something like

但是,如果我要做类似的事情

string word;
cin >> word;
word = space2underscore(word);
cout << word;

I would just get the first word, "hello".

我只会得到第一个词,“你好”。

Does anybody know a fix for this?

有人知道解决这个问题吗?

回答by Blastfurnace

You've got your getlineissue fixed but I just wanted to say the Standard Library contains a lot of useful functions. Instead of a hand-rolled loop you could do:

您的getline问题已解决,但我只想说标准库包含许多有用的功能。您可以执行以下操作,而不是手动循环:

std::string space2underscore(std::string text)
{
    std::replace(text.begin(), text.end(), ' ', '_');
    return text;
}

This works, it's fast, and it actually expresses what you are doing.

这很有效,速度很快,而且它实际上表达了你在做什么。

回答by Evan Teran

The problem is that cin >> wordis only going to read in the first word. If you want to operate on a whole like at a time, you should use std::getline.

问题是cin >> word只能读取第一个单词。如果你想一次操作一个整体,你应该使用std::getline.

For example:

例如:

std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;

Also, you may want to check that you actually were able to read a line. You can do that like this:

此外,您可能想要检查您是否真的能够阅读一行。你可以这样做:

std::string s;
if(std::getline(std::cin, s)) {
    s = space2underscore(s);
    std::cout << s << std::endl;
}


Finally, as a side note, you could probably write your function in a cleaner way. Personally I would write it like this:

最后,作为旁注,您可能可以以更简洁的方式编写函数。我个人会这样写:

std::string space2underscore(std::string text) {
    for(std::string::iterator it = text.begin(); it != text.end(); ++it) {
        if(*it == ' ') {
            *it = '_';
        }
    }
    return text;
}

Or for bonus points, use std::transform!

或获得奖励积分,请使用std::transform!

EDIT:If you happen to be lucky enough to be able to use c++0x features (and I know that's a big if) you could use lambdas and std::transform, which results in some very simple code:

编辑:如果您碰巧能够使用 c++0x 功能(我知道这是一个很大的 if),您可以使用 lambdas and std::transform,这会产生一些非常简单的代码:

std::string s = "hello stackoverflow";
std::transform(s.begin(), s.end(), s.begin(), [](char ch) {
    return ch == ' ' ? '_' : ch;
});
std::cout << s << std::endl;

回答by Platinum Azure

The problem is with your understanding of std::cinfrom the iostreamlibrary: Using the >>operator on a stream with an std::stringas the right-hand-side argument only takes one word at a time (using whitespace to separate).

问题是与你的理解std::ciniostream库:使用>>上有一个流运算符std::string的右手边参数只是(用空格分隔),需要一个词在同一时间。

What you want instead is to use std::getline()to get your string.

你想要的是std::getline()用来获取你的字符串。

回答by Ben Crowhurst

For a modern C++1x approach you have the option of std::regex_replace.

对于现代 C++1x 方法,您可以选择std::regex_replace

#include <regex>
#include <string>
#include <cstdlib>
#include <iostream>

using std::cout;
using std::endl;
using std::regex;
using std::string;
using std::regex_replace;

int main( const int, const char** )
{
   const auto target = regex{ " " };
   const auto replacement = string{ "_" };
   const auto value = string{ "hello stackoverflow" };

   cout << regex_replace( value, target, replacement ) << endl;

   return EXIT_SUCCESS;
}

Pros: Less code.

优点:更少的代码。

Cons: Regular expressions can cloud intent.

缺点:正则表达式可能会影响意图。

回答by Erik

Replace

代替

cin >> word;

With

getline(cin, word);