我有一个学生 vector ,每个元素由 ID 和测试答案组成。
ABCTFTFTF(ABC = ID,TFTFTF = 答案)
我试图只检索 TFTFTF 的 block ,并将它们与包含正确答案字符串的字符串进行比较。
我理解它一定是:
学生[i]
创建子字符串(答案开始 = 位置 10,结束于位置 30)
比较子串
根据比较采取行动
但我在句法上真的很挣扎,有人能给我指出正确的方向吗?
- 编辑
尝试过:
void getResults()
{
string found;
for(int i = 0; i < 150; i++)
{
found = students[i].find(answers);
if(found == answers)
{
cout << "Student: " << i << "Passed" << endl;
}
else
{
cout << "Student: " << i << "Failed" << endl;
}
}
}
个人项目——不是家庭作业
我正在关注这个每日 C++ 项目线程:
http://www.cplusplus.com/forum/beginner/75558/
模拟数据:
OMXIZGWA TTFTFTFFTFTTFFFTTFTF
XKVNYUVZ F FTFFFFFT TFFTTTFFF
GGVDSSTQ TFFFTF FTTF TF TFFT
XPYDXVIQ FFTTFT FTFT TFFTTTFT
XVFUMFZL TTFFTFFTFFTFF FFTFFT
(白色字符 = 未给出答案)
* 编辑答案
void getResults()
{
string found;
string foundSubString;
for(int i = 0; i < 150; i++)
{
found = students[i];
foundSubString = found.substr (9,20);
if(foundSubString == answers)
{
cout << "Student: " << i << "Passed" << endl;
}
else
{
cout << "Student: " << i << "Failed" << endl;
}
}
最佳答案
假设:
- 所有 ID 都是唯一的
- 每个 ID 都与一串答案相关联。
这听起来像是字典的工作。 C++ STL 提供了一个方便的 std::map
。
std::string answerKey = "TTFFTF"
std::map<std::string, std::string> studentAnswers;
studentAnswers["student1"] = "TFTTTF";
studentAnswers["student2"] = "FFTFTF";
// more students....
现在您已经定义了数据,您可以定义一个比较函数。假设你想找到错误的数量,你可以这样定义一个原型(prototype):
int compareAnswer(const std::string& correctAnswer, const std::string& valiantAttempt);
(注意:方便的是,这实际上正是来自 string.h 的老式 C 函数 strcmp
所做的)
然后使用函数:
cout << "Student1 has "
<< compareAnswer(answerKey, studentAnswers["student1"])
<< " errors" << endl;
当然,您会使用 for
循环并可能从文件中读取数据等,但我希望这能让您朝着正确的方向前进。
关于c++ - 在字符串 vector 中查找部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11587817/