仅供参考,任何时候你不理解 C++ 函数,你可以谷歌它,你应该在 cplusplus.com 弹出一个很好的解释。这就是我得到我要告诉你的信息的地方。
编辑:正如另一个人所说,cppreference.com 也应该出现,这也是要看的地方。忘记加了,哈哈
string::replace
需要一个起始位置、一个长度和一个字符串来替换它。
您似乎想要的是一个可以接受输入值并将其替换为您想要的任何值的函数。在这种情况下,您似乎想替换任何不是“-”的数字或字符,对吗?
在这种情况下,我将创建一个函数,该函数接受一个字符串引用、一个“shouldReplace”函数和一个将其替换为输入的值。
您说您是初学者,所以以防万一,我将解释什么是参考。本质上,如果您将变量传递给函数并更改它,那么您实际上不会更改该变量,您将更改该变量的副本。这称为“按值传递”。如果您改为通过引用传递,那么您所做的任何更改实际上都会影响您所做的事情。
我们的函数将接收输入字符串并对其进行修改,因为这是最简单的路线,因为string::replace
已经这样做了。
接下来要解释的是如何将函数作为参数传递。再说一次,既然你说你是初学者,我假设你不知道这一点。函数可以存储在变量中并像参数一样传入。我们想创建一个函数,给定一个字符,生成一个关于该字符是否应该被替换的布尔值,然后我们想将它传递给我们的替换函数。
现在是肉和土豆;替换功能。
首先,我们将使用我提到的参数声明函数:
#include <functional>
#include <string>
void conditionalReplaceWith(
string &str, std::function<bool(char)> test, std::string repWith) {
...
}
请注意,为了获取我们使用的字符串引用&str
并获取我们使用标准库的一部分的函数std::function
,我们声明它返回 abool
并将 achar
作为参数。
这意味着当我们传入一个函数时,它应该如下所示:
bool testFuncToPassIn(char c) {
...
}
现在我们有了一个函数,让我们来填充它。
我们想遍历每个字符并测试它是否是我们要替换的字符。如果是,那么我们替换它。如果不是,那么我们继续。
使用stringstream
s 有更好的方法来做到这一点,但既然你暗示你正在尝试这样做string::replace
,我已经使用它来代替。
我也会使用 const 引用,但由于您是初学者,所以此时不值得解释。你还不需要知道。
#include <functional>
#include <string>
void conditionalReplaceWith(
string &str, std::function<bool(char)> test, std::string repWith) {
// Loop over every character. This will work even after modifying str
for(int pos = 0; pos < str.length(); pos++) {
if(test(str[pos])) { // Check if the character should be replaced
str.replace(pos, 1, repWith); // Replace it! Increases str.length()
}
}
}
现在我们需要我们的测试函数:
bool isNotDash(char c) {
return c != '-';
}
让我们把它们放在一起:
#include <iostream>
#include <functional>
#include <string>
void conditionalReplaceWith(
string &str, std::function<bool(char)> test, std::string repWith) {
// Loop over every character. This will work even after modifying str
for(int pos = 0; pos < str.length(); pos++) {
if(test(str[pos])) { // Check if the character should be replaced
str.replace(pos, 1, repWith); // Replace it! Increases str.length()
}
}
}
bool isNotDash(char c) {
return c != '-';
}
int main() {
std::string name, social, userName, password;
std::cout << "Enter your first name, Social Security number (digits only), userID (no spaces within ID), and password (no spaces within password) - with a space between each entry: ";
std::cin >> name >> social >> userName >> password;
conditionalReplaceWith(social, isNotDash, "X");
...
}
最后,如果您想让您的绝密函数使用conditionalReplaceWith
,您可以执行以下操作:
std::string topSecret(std::string password) {
conditionalReplaceWith(password, [](char c) { return true; }, "X");
return password;
}
那一点[](char c) { return true; }
是一个匿名函数。它在那里声明了一个函数。
无论如何,这不会更改密码,因为请记住,密码是按值传递的。在这里修改它就像是std::string passwordCopy(password)
先说并复制它。
是的。你去吧。