我该如何在C#中解决StringBuilder问题?

问题描述 投票:2回答:2

我在做什么:使用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计算。问题的数量增加,效率低下。

[问题:如何创建包含变量的问题,以便有效地在同一问题结构中提供变化?

c# string stringbuilder
2个回答
1
投票

考虑使用switch语句

        Random rnd = new Random();
        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 question;

        switch (rnd.Next(1, 4)) {
            case 1: {
                question = "What is " + a + " + " + a + " ?";

                break;
            }
            case 2: {
                question = "What is " + a + " + " + b + " ?";

                break;
            }
            case 3: {
                question = "What is " + (a * b) + " + " + c + " ?";

                break;
            }
            default: {
                question = "Default Value";

                break;
            }
        }

C#8:

        question = rnd.Next(1, 4) switch {
            1 => "What is " + a + " + " + a + " ?",
            2 => "What is " + a + " + " + b + " ?",
            3 => "What is " + (a * b) + " + " + c + " ?",
            _ => "Default Value"
        };

1
投票

我建议使用Dictionary<TKey, TValue>

 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);     

 var dict = new Dictionary<int, string>
 {
     { 1, "What is " + a + " + " + a + " ?" },
     { 2, "What is " + a + " + " + b + " ?" },
     { 3, "What is " + (a * b) + " + " + c + " ?" },
 };
 var question = dict[questionNumber];
© www.soinside.com 2019 - 2024. All rights reserved.