English 中文(简体)
如何简化我实施基本剖腹产加密算法 c#?
原标题:How to simplify my implementation of a basic Caesar Shift Encryption algorithm c#?
  • 时间:2011-03-17 09:20:15
  •  标签:
  • c#

因此,我最近决定,我的编码风格有些模糊。 我从来都无法进入一个阶段,在这个阶段,我可以不惜把它简化为效率较低的法典。

我正处在一个团队式的状态,另一天试图利用TDD来编出一个言语的总结特征。 当我坐在驾车座时,我把大部分时间用在“强硬”。 内容和发言内容。 我gu问,为什么如此复杂,并有一个更简单的休养人,把必要的价值观归还给他,并且有一些条件让他离开休养假。

因此,我的问题是——下面是我写成的一些法典,它只使用较低病例字母和没有空间,就剖腹产进行加密。 单位测试通行证,我认为我已经执行了可能出现的各种条件。

简言之,你会如何简化以下法典,使之更加可读和更有效率?

我赞赏这方面的帮助,因为当日末,我需要使我的编码风格变得不那么简单、更简单,而且不能说出最好的开端。

卡车

C部分:

 public static string Encrypt(string inputString, int shiftPattern)
    {
        StringBuilder sb = new StringBuilder();

        char[] alphabet = {  a ,  b ,  c ,  d ,  e ,  f ,  g ,  h ,  i ,  j ,  k ,  l ,  m ,  n ,  o ,  p ,  q ,  r ,  s ,  t ,  u ,  v ,  w ,  x ,  y ,  z  };

        //y = x + 3 (mod 26)
        foreach (var letter in inputString.ToLower())
        {
            if (!alphabet.Contains(letter))
            {
                return "The " + letter + " Character was not in the sample set, please ensure you only use letters";
            }

            var res = Array.IndexOf(alphabet, letter) + (shiftPattern % 26);

            if (res >= 26)
            {
                res = res - alphabet.Length;

                sb.Append(alphabet[res]);
            }

            else if (res < 0)
            {
                res = alphabet.Length + res;
                sb.Append(alphabet[res]);
            }

            else

                sb.Append(alphabet[res]);
        }
        return sb.ToString();
    }
问题回答

1.- Put sb.Append(alphabet[res]) only once outside the conditionals.
2.- Consider throw an exception instead of return a message... so later you can easily check that the operation works propertly. You should also consider let the character As Is if It s not pressent in your alphabet definition. It will allow you deal with whitespaces, etc.
3.- Check that the last conditional are really necessary. At first view... It looks that it could be safety removed... so confirm it. We can add a Math.Abs function to avoid problems with negative numbers in ShiftPattern.
4.- In some places you use alphabet.Length, and in other places you use 26. Use always alphabet.Length.
5.-Don t check that (res >= 26), you can do directly a MOD operation.

    public static string Encrypt(string inputString, int shiftPattern)
            {
                StringBuilder sb = new StringBuilder();

                char[] alphabet = {  a ,  b ,  c ,  d ,  e ,  f ,  g ,  h ,  i ,  j ,  k ,  l ,  m ,  n ,  o ,  p ,  q ,  r ,  s ,  t ,  u ,  v ,  w ,  x ,  y ,  z  };

                //y = x + 3 (mod 26)
                foreach (var letter in inputString.ToLower())
                {
                    if (!alphabet.Contains(letter)) //Consider throwing and exception instead
                    {
                        return "The " + letter + " Character was not in the sample set, please ensure you only use letters";
                    }

                    var res = Array.IndexOf(alphabet, letter) + (Math.Abs(shiftPattern) % alphabet.Length);
                    res = res % alphabet.Length
                    sb.Append(alphabet[res]);
                }
                return sb.ToString();
            }

你们可以放弃一行的规律,一行。

        StringBuilder sb = new StringBuilder();
        foreach (var letter in inputString.ToLower())
            sb.Append((char)((((letter -  a ) + shiftpattern)%26) +  a ));

In: zombie & transformation by 1

Out: apncjf

There is no need to hold the complete alphabet list.
Also, if you don t support spaces then your messages will be like roman latin, without spaces...

    public static string Encrypt(string inputString, int shiftPattern)
    {
        StringBuilder sb = new StringBuilder();
        foreach(char letter in inputString.ToLower())
        {
            int encryptedValue = 0;
            if (letter ==    )
            {
                encryptedValue =    ;
            }
            else
            {
                encryptedValue = (((letter -  a ) + shiftPattern) % 26) +  a ;
            }

            sb.Append((char)encryptedValue);
        }
        return sb.ToString();
    }

我建议如下:

  1. in case or more than two conditions use Switch- Case.
  2. Instead of char[] or any variable declaration use var if using 3.0 or above
  3. For and Foreach loops are avoided using lambda expressions.
  4. Make such methods static and put it in some common class that can be shared globally.

更良好做法。 喷气镜的耐水器

对算法作了一些改动:

static char[] alphabet = {  a ,  b ,  c ,  d ,  e ,  f ,  g ,  h ,  i ,  j ,  k ,  l ,  m ,  n ,  o ,  p ,  q ,  r ,  s ,  t ,  u ,  v ,  w ,  x ,  y ,  z  };

public static string Encrypt(string inputString, int shiftPattern)
{
    if (inputString == null) return null;
    if (shiftPattern <= 0)
    {
        shiftPattern = alphabet.Length + shiftPattern % alphabet.Length;
    }

    var chars = inputString.Select(c =>
    {
        var index = Array.IndexOf(alphabet, char.ToLower(c));
        if (index == -1) return c;

        var result = alphabet[(index + shiftPattern) % 26];
        return char.IsLower(c) ? result : char.ToUpper(result);
    });

    return new string(chars.ToArray());
}
  • Manage the null string case.
  • Non-cypherable chars are kept as-is (debatable in a cypher...)
  • Just use linq instead of old style loops and builders.
  • Manage upper case
  • Shorter, while still understandable without problems.
  • I separated the return from the select for clarity here, in normal code if the return ... Select line didn t go over the column limit for the code base I would have combined the two.




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签