11

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

到目前为止我所拥有的。

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

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

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

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

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

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

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

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

4

5 回答 5

25

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

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

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

于 2011-03-09T22:47:29.397 回答
15

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

例如:

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

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

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

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

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

或者对于奖励积分,使用std::transform

编辑: 如果您碰巧能够使用 c++0x 功能(我知道这是一个很大的假设),您可以使用 lambdas 和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;
于 2011-03-09T21:53:13.427 回答
5

问题在于您对库的理解std::ciniostream>>流上使用运算符并以 anstd::string作为右侧参数一次只需要一个单词(使用空格分隔)。

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

于 2011-03-09T21:53:07.733 回答
1

对于现代 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;
}

优点:更少的代码。

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

于 2017-05-05T23:48:35.947 回答
-1

代替

cin >> word;

getline(cin, word);
于 2011-03-09T21:53:36.143 回答