简体   繁体   English

C#编程分配

[英]C# Programming Assignment

The teacher wants me to create 2 files & insert random characters inside. 老师要我创建2个文件并在其中插入随机字符。 Both files should be the same length. 两个文件的长度应相同。 In one file a keyword "Hello" should be inserted randomly. 在一个文件中,关键字“ Hello”应随机插入。

I did this for the first file: 我是针对第一个文件执行此操作的:

var stringChars = new char[100];
var random = new Random();
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


for (int i = 0; i < stringChars.Length; i++)
{
    stringChars[i] = chars[random.Next(chars.Length)];

}

I did this for the second file: 我为第二个文件做了这个:

   var stringChars2 = new char[100];
   var random2 = new Random();
   var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZxxxxx";

   for (int i = 0; i < stringChars2.Length; i++)
   {
       stringChars2[i] = chars2[random2.Next(chars2.Length)];

   }


   string string2 = new string(stringChars2);
   string2 = string2.Replace("x", "\"Hello\"");

My problem is I don't know how to make the length of both files equal with the string replace trick. 我的问题是我不知道如何用字符串替换技巧使两个文件的长度相等。 The second file will always be longer. 第二个文件将始终更长。

Here's an object oriented approach. 这是一种面向对象的方法。 I emphasize this approach since you have to perform similar operations multiple times (two). 我强调这种方法,因为您必须多次执行类似的操作(两次)。 Thus, you shouldn't repeat yourself (google DRY prinicpal). 因此,您不应该重复自己(google DRY prinicpal)。

I won't tell you how to use these methods, you can figure that our for yourself: 我不会告诉您如何使用这些方法,您可以自己了解一下:

public static class StringManipulation
{
    public static string GetXRandomCharacters(int x)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        var random = new Random();
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int i = 0; i < stringChars.Length; i++)
        {
            sb.Append(chars[random.Next(chars.Length)]);
        }

        return sb;
    }

    public static string InjectWordAtRandom(string str, string word)
    {
        var random = new Random();
        int start = random.Next(str.Length - word.Length);

        str.Remove(start, word.Length).Insert(start, word);
    }
}

Hint: I have provided static methods but you don't have to do it that way. 提示:我提供了静态方法,但您不必那样做。 Try removing static from the method headers and creating an instance of the class to access it's properties. 尝试从方法标题中删除static元素,并创建该类的实例以访问其属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM