查找字符串是否包含字符串,并处理附加的数字
Finding if a string contains a string and manipulating attached numbers
假设作为输入的一部分,一个用户输入nrt:x来告诉程序计算x的第n个根。如果我想把n和x发送到另一个方法来简化第n个根号,我想我可以使用std::string::find来查找"rt:"。如果find返回true,那么我需要将n和x发送到另一个方法,但在找到"rt:"之后,我该怎么做呢?例如,用户输入7rt:3。对于"rt:",Find将返回true,然后我如何将3和7发送到另一个方法?
if(std::string::find(rt:)) {
//manipulate numbers before/after rt: from user input
if(result will be an int) {
nthRoot(double n, double x);
}
If(result will not be an int) {
nthRootSimplify(double n, double x);
}
}
void nthRoot(double x, double n){
double nthRootSol = pow(x, double(1 / n));
}
编辑:在你的帮助下,我写的代码是一个解决方案。任何建议都很好。如果"n"或"z"大于1 int,我会发现自己遇到了问题。
void findNthRoot(string x) {
if(x.find("rt:") != string::npos) {
unsigned position = x.find("rt:");
cout << position << endl;
double n = position - 1;
cout << n << endl;
double z = position + 3;
cout << z << endl;
string str1 = x.substr(n, 1);
string str2 = x.substr(z);
cout << str1 << endl;
cout << str2 << endl;
}
}
int main() {
findNthRoot("2 - 1+3rt:4");
return 0;
}
输出为:7.6.103.4.最重要的是"3"answers"4"是str1和str2 的值
如果假设输入总是以n开头,以部首下的数字结尾,则可以使用std::string::front()
访问第一个元素,使用std::string::back()
访问最后一个元素。
find
将不返回true
。这样的find
是非常无用的。实际的std::string::find
返回找到的字符串的位置。
知道了位置,现在可以使用std::string::substr
将字符串分为"之前"answers"之后"部分。
相关文章:
- 如何检查一个c++字符串中有多少相同的字符/数字
- 在 c++ 中查找字符串中没有循环的数字总和
- 将数字转换为填充字符串
- 递归形成字符串中所有数字字符的中间和?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- C++ python 中的函数返回数字而不是字符串
- C++:从文件中读取字符串和整数,并获得最大数字
- 以C++格式将字符串转换为数字
- C++关于数字的字符串数组
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 用C++将浮点数字转换为本地化字符串
- 如何在c++中将字符串中的所有数字保存到多维数组中
- 列出所有 N 位数字,并带有 [字符串] 数字
- 如何将字符串数字转换为各个数字的整数数组
- 如何将字符串/数字排序添加到 QSortFilterProxyModel 派生类
- 将std::字符串数字转换为十六进制数字
- 在c++ /Qt中拆分Lua函数调用的混合字符串/数字参数列表
- 获取字符串数字的精度