Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to simplify my implementation of a basic Caesar Shift Encryption algorithm c#?
    primarykey
    data
    text
    <p>So I have recently decided that my coding style is somewhat clunky. The trouble is I never seem to be able to get to a stage where I can figure out the way of simplifying it into less lines of more efficient code.</p> <p>I was in a team coding situation the other day trying to code a word wrapping feature using TDD. When I was in the driving seat I spent most of my time with String.Split() and if statements this and if that. The guy I was coding with asked why so complex and went with the simpler recursive one liner that returned the values required and with a few conditions to boot him out of the recursive loop when he was done.</p> <p>So my question is thus – Below is some code that I have written to do a Caesar Shift Encryption on a string input using only lower case alphabet and no spaces. The unit tests pass and I believe I have implemented the various conditions that may occur.</p> <p>In a nut shell how would you guys simplify the code below to make it more readable and more efficient?</p> <p>I appreciate the help on this, because at the end of the day I need to make my coding style less verbose and more simplistic and can’t figure out the best place to start.</p> <p>Cheers</p> <p>Code in C#:</p> <pre><code> 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 &gt;= 26) { res = res - alphabet.Length; sb.Append(alphabet[res]); } else if (res &lt; 0) { res = alphabet.Length + res; sb.Append(alphabet[res]); } else sb.Append(alphabet[res]); } return sb.ToString(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload