我所做的: 使用StringBuilder
替换字符串中的变量,生成包含变化的问题。
string question;
void CreateNewQuestion()
{
Random rnd = new Random();
int questionNumber = rnd.Next(1, 4); //Generate a random question number
int a = rnd.Next(1, 10); //Create random numbers so the question is different each time
int b = rnd.Next(1, 15);
int c = rnd.Next(1, 15);
string q = questionNumber.ToString();
StringBuilder sbq = new StringBuilder("Question" +q);//StringBuilder is now called to replace the randomly called for question with its new variables
sbq.Replace("Question1", $"What is {a} + {a} ?");
sbq.Replace("Question2", $"What is {a} + {b} ?");
sbq.Replace("Question3", $"What is {a*c} + {a} ?"");
question = sbq.ToString();
}
问题: 如果字符串q
(正在修改的字符串)=“Question1”,StringBuilder.Replace
不会在 sb.Replace(“Question1”...并仍将计算第2和第3个问题。 因此,随着问题数量的增加,效率也会变得低下。
问题: 如何以高效的方式创建包含变量的问题,以便在相同的问题结构内提供变化?
$" {a} + {b} 是多少?"
. 这样做可以很大程度上帮助您,特别是在字符串连接符“+”与数学符号“+”混用的情况下。 - Alvin Sartor"What is {a} + {b}?"
放入数组或字典中,并按问题编号查找它们。将它们设置为格式化字符串,以便仍然可以填充空缺。请参见https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated - Robert Harvey