回答
没有相应的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::string
和std::string
方法完全使用std::replace
作为其他的答案已经建议
std::replace(string, string + strlen(string), ' ', '_');
,或者如果你已经知道字符串的长度
std::replace(string, string + len, ' ', '_');
但请记住,你不能修改一个常量字符串。
如果你想要做手工,c风格
static inline void manual_c_string_replace(char *s, char from, char to)
{
for (; *s != 0; ++s)
if (*s == from)
*s = to;
}
std :: string函数非常昂贵。我需要做这100万次。它会减慢速度。 – Manish 2013-03-07 08:51:41
@ user15662然后使用'std :: replace',如其他答案所示。 – 2013-03-07 09:08:55
有std::replace
#include <algorithm>
...
std::replace (s.begin(), s.end(), ' ', '_');
有std::replace
功能
std::replace(s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
与此答案惊人的相似http: // stackoverflow.com/a/2896627/597607 – 2013-03-07 08:37:43
是的,有在<algorithm>
定义std::replace()
:
#include <algorithm>
#include <string>
int main() {
std::string input("A B C");
std::replace(input.begin(), input.end(), ' ', '_');
}
- 1. C#在替换函数中不接受'\'
- 2. 在VBA中替换函数
- 3. 在std :: string中替换函数在C++中给出问题
- 4. C++如何选择性替换空函数中的函数
- 5. 替换CF9中的函数
- 6. 用C替换函数定义
- 7. 调试字符串替换函数C
- 8. 函数用post_color替换pre_color使用c
- 9. 替换字符串函数C++
- 10. JavaScript替换函数
- 11. xslt替换函数
- 12. Python替换函数
- 13. 在php中有替换函数吗?像JavaScript替换()
- 14. 在绑定函数中替换文本
- 15. 在Delphi Prism中替换CharInSet函数
- 16. 在Matlab中替换函数'transformPointsForward'
- 17. 在vb.net中创建替换函数
- 18. 在MongoDB中替换()MapReduce映射函数
- 19. 在C#ASP.NET中使用RegEx替换函数
- 20. 在C中使用正则表达式替换函数夏普
- 21. VIM:替换当前C/C++函数中所有字的出现
- 22. 用全局替换函数替换函数
- 23. 在haskell中替换复合函数中的函数
- 24. 如何在C#中替换数组值?
- 25. c#替换整数
- 26. 在C#中使用“\ /”替换“\”#
- 27. 在C#中,替换 “\\” 到 “\”
- 28. 在C中替换字符#
- 29. 有没有办法替换C++中的方法中的函数
- 30. preg替换函数和http://?
考虑'的std :: string'你的目的... – 2013-03-07 08:33:19
[可能的复制(http://stackoverflow.com/q/5878775/1084416) – 2013-03-07 08:33:42
我有字符串(char *),所以不想使用std :: string函数。 – Manish 2013-03-07 08:40:54