用下划线替换空格

问题描述:

我想写一些将用下划线替换字符串中的所有空格。用下划线替换空格

我到目前为止。

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

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

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

这将输出“hello_*”,这正是我想要的。

但是,如果我是这样做

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

,我只想拿到的第一个字,“你好”。

有没有人知道这个问题的解决方法?

问题是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特性的(我知道这是个很大的可能),你可以使用lambda表达式和std::transform,这会导致一些非常简单的代码:

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

不好意思,但是你正在混淆你是否使用'std ::'或不。 (虽然在技术上,你的代码可以在顶部使用std :: cout;' – 2011-03-09 21:57:27

+0

@ Platinum Azure:你说得对,我个人喜欢使用明确的'std ::',但是我复制了一些OP的代码我的例子。我会把它清理干净。 – 2011-03-09 21:59:27

+0

谢谢先生!我的程序现在运行正常:) – 2011-03-09 22:01:44

问题是与你的距离iostream库的std::cin理解:在与std::string为右手边参数流使用>>操作者只需要一次一个字(用空格分隔)。

你想要的是使用std::getline()来得到你的字符串。

更换

cin >> word; 

随着

getline(cin, word); 

你已经修复了你的getline问题,但我只想说标准库包含很多有用的功能。你可以这样做,而不是一个手卷循环:

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

这个工程,它很快,它实际上表达了你在做什么。

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

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

    return EXIT_SUCCESS; 
} 

优点:更少的代码。

缺点:正则表达式可以云意图。