我需要将字符串中的两个值交换为一个(c++)
I need to swap out two values in a string for one (C++)
我正在制作罗马数字转换器。除了最后还有一个问题,我已把一切都解决了。
字符串看起来像IVV
我需要把它改成IX
我在每个新字母处拆分字符串,然后将它们附加回去,然后使用if语句查看它是否包含2个"V"。我想知道是否有更简单的方法来做到这一点
使用std::string
可以极大地帮助您,因为您可以利用其搜索和替换功能。您将希望从find
函数开始,它允许您搜索字符或字符串,并返回您正在搜索的内容存在的索引,如果搜索失败,则返回npos
。
你可以调用replace
,传递find
返回的索引,你想要替换的字符数和替换范围的内容。
下面的代码应该可以帮助你开始。
#include <string>
#include <iostream>
int main()
{
std::string roman("IVV");
// Search for the string you want to replace
std::string::size_type loc = roman.find("VV");
// If the substring is found replace it.
if (loc != std::string::npos)
{
// replace 2 characters staring at position loc with the string "X"
roman.replace(loc, 2, "X");
}
std::cout << roman << std::endl;
return 0;
}
您可以使用std string
find
和rfind
操作,这些操作可以找到输入参数的第一个和最后一个出现的位置,检查它们是否不相等,您将知道
回答更新
#include <string>
int main()
{
std::string x1 = "IVV";
if (x1.find('V') !=x1.rfind('V'))
{
x1.replace(x1.find('V'), 2, 'X');
}
return 0;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在for循环中包含两个索引值的测试条件
- 在声明中合并两个常量"std::set"(不是在运行时)
- 如何使用OpenMP并行这两个循环