根据用户输入从多项选择题中提取答案
extract answer from multiple choice question based on user input
问题:
用户输入答案(a、b、c、d)。该程序应从数据库中匹配并获得准确的完整答案。
示例:
What is 9 + 1?
a. 9
b. 10
c. 5
d. 21
当用户写入 (b) 时,程序应该得到答案 (10)
这是我所做的:
private string Answer(string question, string answer)
{
string userans = null;
try
{
if (question != null || answer != null)
{
string[] inputSplit = question.ToString().Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < inputSplit.Length; i++)
{
if (inputSplit[i].Contains(answer + "."))
{
userans = inputSplit[i].Split('.')[1];
return userans;
}
else
{
userans = null;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return userans;
}
问题是:
我如何避免使用 Loop 并提取相同的结果?或者有更好的方法吗?
您可以使用 Regex 为每个多项选择选项创建组,然后以这种方式提取答案。
此解决方案假定您只有 4 个选项并使用您在问题中使用的格式。您还需要添加一些输入验证,但这是一般的想法。
public string GetAnswer(string question, string userAnswer)
{
var regexPattern = "a\. (\w+)\r\nb\. (\w+)\r\nc\. (\w+)\r\nd\. (\w+)";
var match = Regex.Match(question, regexPattern);
if (match.Success)
{
switch (userAnswer)
{
case "a":
return match.Groups[1].Value;
case "b":
return match.Groups[2].Value;
case "c":
return match.Groups[3].Value;
case "d":
return match.Groups[4].Value;
}
}
throw new Exception("Failed to parse the question.");
}
问题: 用户输入答案(a、b、c、d)。该程序应从数据库中匹配并获得准确的完整答案。
示例:
What is 9 + 1?
a. 9
b. 10
c. 5
d. 21
当用户写入 (b) 时,程序应该得到答案 (10)
这是我所做的:
private string Answer(string question, string answer)
{
string userans = null;
try
{
if (question != null || answer != null)
{
string[] inputSplit = question.ToString().Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < inputSplit.Length; i++)
{
if (inputSplit[i].Contains(answer + "."))
{
userans = inputSplit[i].Split('.')[1];
return userans;
}
else
{
userans = null;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return userans;
}
问题是: 我如何避免使用 Loop 并提取相同的结果?或者有更好的方法吗?
您可以使用 Regex 为每个多项选择选项创建组,然后以这种方式提取答案。
此解决方案假定您只有 4 个选项并使用您在问题中使用的格式。您还需要添加一些输入验证,但这是一般的想法。
public string GetAnswer(string question, string userAnswer)
{
var regexPattern = "a\. (\w+)\r\nb\. (\w+)\r\nc\. (\w+)\r\nd\. (\w+)";
var match = Regex.Match(question, regexPattern);
if (match.Success)
{
switch (userAnswer)
{
case "a":
return match.Groups[1].Value;
case "b":
return match.Groups[2].Value;
case "c":
return match.Groups[3].Value;
case "d":
return match.Groups[4].Value;
}
}
throw new Exception("Failed to parse the question.");
}