我是C++编程的新手,但我有Java经验.我需要有关如何将对象传递给C++中的函数的指导.
我是否需要传递指针,引用或非指针和非引用值?我记得在Java中没有这样的问题,因为我们只传递了保存对象引用的变量.
如果您还可以解释在哪里使用这些选项,那将会很棒.
有没有办法用另一个字符串替换所有出现的子字符串std::string
?
例如:
void SomeFunction(std::string& str)
{
str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
Run Code Online (Sandbox Code Playgroud) 给定一个(char*)字符串,我想找到所有出现的子字符串并用替换字符串替换它.我没有看到任何在<string.h>中实现此功能的简单函数
我怎么能用C++中的另一个子字符串替换字符串中的子字符串,我可以使用哪些函数?
eg: string test = "abc def abc def";
test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring
Run Code Online (Sandbox Code Playgroud) 如果s
是a std::string
,那么是否有如下函数?
s.replace("text to replace", "new text");
Run Code Online (Sandbox Code Playgroud) 我发现这是另一个堆栈问题:
//http://stackoverflow.com/questions/3418231/c-replace-part-of-a-string-with-another-string
//
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
Run Code Online (Sandbox Code Playgroud)
和我的方法:
string convert_FANN_array_to_binary(string fann_array)
{
string result = fann_array;
cout << result << "\n";
replaceAll(result, "-1 ", "0");
cout << result << "\n";
replaceAll(result, "1 ", "1");
return result;
}
Run Code Online (Sandbox Code Playgroud)
其中,对于此输入: …
如何从字符串中删除模式的所有实例?
string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";
Run Code Online (Sandbox Code Playgroud) 在我能想到的每种语言中,除了C++之外,函数Replace实际上替换了字符串的所有部分,而C++的字符串类不支持如下的简单操作:
string s = "Hello World";
s = s.Replace("Hello", "Goodbye");
echo s; // Prints "Goodbye World"
Run Code Online (Sandbox Code Playgroud)
这似乎是任何类型的字符串替换函数的最常见用法,但在C++中似乎没有标准的替换函数.我在这里错过了什么吗?
编辑:我知道在标准库中没有这样的内置替换函数 - 我想知道是否有一个或多或少的标准实现由标准算法或类似的东西.
我试图找到一种方法来用新行替换文件中包含字符串的行。
如果文件中不存在该字符串,则将其附加到文件中。
有人可以提供示例代码吗?
编辑:无论如何,如果我需要替换的行位于文件末尾?