FrodoBaggins
FrodoBaggins

Reputation: 43

String substitution (C#)

Programming in c#.
I'm trying to substitute every char in a string with another char (Encryption), but I need some help. I was going to do this using two arrays, one with the alphabet in it, then the other with the substitute values, but I realized I'd have to do a else-if the size of the whole alphabet, which I don't really have time for. I'd like to know if there is an easier, faster way. This is what I have so far

private string EncryptFn(string Sinput)
{
    string STencryptedResult = "Null for now";
    char[] CAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
    char[] Encrypt = "QWERTYUIOPASDFGHJKLZXCVBNM".ToCharArray();

    return STencryptedResult;
}

Thanks

Upvotes: 3

Views: 1221

Answers (3)

Andrew Kennan
Andrew Kennan

Reputation: 14157

You could use a Dictionary:

var map = new Dictionary<char,char> {
  { 'A', 'Q' },
  { 'B', 'W' },
  // etc
};

Then it becomes pretty easy to map each char with something like this:

var result = new StringBuilder();
foreach( var fromChar in inputString ) {
  char toChar;
  if( ! map.TryGetValue(fromChar, out toChar) ) {
    // Do something with missing char
  }
  result.Append(toChar);
}

Upvotes: 6

Jonathan Wood
Jonathan Wood

Reputation: 67195

It isn't a very strong encryption, but you the following version would be extremely efficient and requires very little data to define the encryption:

private string EncryptFn(string Sinput)
{
    string coding = "QWERTYUIOPASDFGHJKLZXCVBNM";

    StringBuilder result = new StringBuilder();
    foreach (char c in Sinput)
    {
        int index = (Char.ToUpper(c) - 'A');
        if (index >= 0 && index < coding.Length)
            result.Append(coding[index]);
        else
            result.Append(c);
    }
    return result.ToString();
}

Upvotes: 5

James Shaw
James Shaw

Reputation: 839

You might consider BitWise operations, they work great for encrypting and decrypting data. See the following.

Byte array cryptography

Upvotes: 0

Related Questions