【发布时间】:2021-11-02 16:52:03
【问题描述】:
我的代码应该从具有两组元素的输入字符串中找到匹配的整数值...我的方法是使用 [i] 循环和 [ j] 循环遍历元素以查找以查看哪些数字匹配以及它们是否将其存储在匹配的字符串中...但我注意到逗号和刺中的空格也在进行比较...是否有如何将字符串 elements1 和 elements2 转换为整数值并进行比较?另外,我是否必须将匹配的整数值转换回字符串?一个例子是
输入:{"1, 3, 4, 7, 13", "1, 2, 4, 13, 15"}
输出:1,4,13
请帮帮我,我觉得我快解决这个问题了!
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
string FindIntersection(string strArr[], int arrLength)
{
// code goes here
bool num_matched;
string matched = "";
string elements1 = strArr[0];
string elements2 = strArr[1];
cout << "elemets 1: " << elements1 << '\n';
cout << "elemets 2: " << elements2 << '\n';
for (int i = 0; i < elements1.length(); i++)
{
num_matched = true;
char num1 = elements1[i];
for (int j = 0; j < elements2.length(); j++)
{
char num2 = elements2[j];
if (num1 == num2)
{
num_matched = true;
break;
}
else
{
num_matched = false;
}
}
if (num_matched == true)
{
matched += num1;
}
}
return matched;
// return strArr[0];
}
int main(void)
{
string A[] = { "1, 3, 4, 7, 13", "1, 2, 4, 13, 15" };
int arrLength = sizeof(A) / sizeof(*A);
cout << '\n' << "matchaed number in both elemets:" << '\n' << FindIntersection(A, arrLength);
return 0;
}
我得到的当前输出如下: " 元素 1:1、3、4、7、13 元素 2:1、2、4、13、15
两个元素中的匹配数字: 1, 3, 4, , 13 "
【问题讨论】:
-
"有没有办法可以将字符串 elements1 和 elements2 转换为整数值并进行比较?" -- 这是你的问题。专注于转换为整数值,在问题后面移动上下文,并删除处理“匹配”的代码。
-
如果您能将您的问题与Convert String with commas separated values to vector<int> 和Copying a set<int> to comma-separated std::string 区分开来,这也可能会有所帮助
标签: c++ string for-loop integer compare