2013-03-07 107 views
-5

我有一个字符串A B C.我需要用C++中的下划线(_)替换空格。有没有像我们在Perl或Java中的功能?在C++中替换函数

输入:

char* string = "A B C" 

输出

A_B_C 
+1

考虑'的std :: string'你的目的... – 2013-03-07 08:33:19

+0

[可能的复制(http://stackoverflow.com/q/5878775/1084416) – 2013-03-07 08:33:42

+0

我有字符串(char *),所以不想使用std :: string函数。 – Manish 2013-03-07 08:40:54

回答

1

没有相应的replace成员函数。

您必须先为search的空间,然后使用std::string::replace

char *string = "A B C"; 
std::string s(string); 
size_t pos = s.find(' '); 
if (pos != std::string::npos) 
    s.replace(pos, 1, "_"); 

只需char*,把它先在std::string,然后应用在这里的答案之一。

如果你想避免std::stringstd::string方法完全使用std::replace作为其他的答案已经建议

std::replace(string, string + strlen(string), ' ', '_'); 

,或者如果你已经知道字符串的长度

std::replace(string, string + len, ' ', '_'); 

但请记住,你不能修改一个常量字符串。

如果你想要做手工,风格

static inline void manual_c_string_replace(char *s, char from, char to) 
{ 
    for (; *s != 0; ++s) 
     if (*s == from) 
      *s = to; 
} 
+1

std :: string函数非常昂贵。我需要做这100万次。它会减慢速度。 – Manish 2013-03-07 08:51:41

+0

@ user15662然后使用'std :: replace',如其他答案所示。 – 2013-03-07 09:08:55

6

std::replace

#include <algorithm> 
... 
std::replace (s.begin(), s.end(), ' ', '_'); 
4

std::replace功能

std::replace(s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y' 
+2

与此答案惊人的相似http: // stackoverflow.com/a/2896627/597607 – 2013-03-07 08:37:43

4

是的,有在<algorithm>定义std::replace()

#include <algorithm> 
#include <string> 

int main() { 
    std::string input("A B C"); 
    std::replace(input.begin(), input.end(), ' ', '_'); 
}