【发布时间】:2018-07-31 17:05:28
【问题描述】:
我想用取决于分隔符之间的子字符串的东西替换字符串中的子字符串。小例子:
我得到了字符串
The result is __--__3__--__.
还有一个函数
int square(int x): { return x*x };
现在我想只输出带有结果的字符串,不带分隔符,所以:
The result is 9.
我已经尝试了几种算法,但都没有奏效。 最好的尊重
我最好的尝试:
const std::string emptyString = "";
std::string ExtractString(std::string source, std::string start, std::string end)
{
std::size_t startIndex = source.find(start);
// If the starting delimiter is not found on the string
// stop the process, you're done!
//
if (startIndex == std::string::npos)
{
return emptyString;
}
// Adding the length of the delimiter to our starting index
// this will move us to the beginning of our sub-string.
//
startIndex += start.length();
// Looking for the end delimiter
//
std::string::size_type endIndex = source.find(end, startIndex);
// Returning the substring between the start index and
// the end index. If the endindex is invalid then the
// returned value is empty string.
return source.substr(startIndex, endIndex - startIndex);
}
int square(int x): { return x*x };
int main() {
std::string str = "The result is __--__3__--__.";
std::string foundNum = ExtractString(str, "__--__", "__--__");
int foundNumInt = atoi(foundNum.c_str());
int result = square(foundNumInt);
std::string toReplace = "__--__";
toReplace.append(foundNumInt);
toReplace.append("__--__");
str.replace(str.begin(), str.end(), toReplace, result);
}
问题是:如何获取给定的第一个字符串(The result is __--__<number>__--__.>,从中获取数字,对该数字执行函数,然后以类似于 The result is <number squared> 的字符串结尾。
【问题讨论】:
-
使用
std::regex无论如何你没有表现出任何努力,这似乎是一个家庭作业。 -
The result is __--__3__--__.的用途是什么,比如空白点是什么意思?我不完全是您想要替换的内容以及您想要做的事情...... -
@CU_dev 假设我从服务器获得了带有此消息的输入。我想用函数调用 square(3) 的结果替换子字符串“__ -3--__”(对不起,粗体字符,这是stackoverflow的格式)
-
所以你想找到 3,然后用答案替换
is之后的所有内容? -
如果代码实际上是 C++ 而不是其他东西,那就太好了。 请显示您尝试过的代码。