Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a ROT13 in one line?

I have the following code which I would like to see as a oneliner. However, since I am very new to C#, I currently have no clue on how to do this...

Code:

static string ROT13 (string input)
{
    if (string.IsNullOrEmpty(input)) return input;

    char[] buffer = new char[input.Length];

    for (int i = 0; i < input.Length; i++)
    {
        char c = input[i];
        if (c >= 97 && c <= 122)
        {
            int j = c + 13;
            if (j > 122) j -= 26;
            buffer[i] = (char)j;
        }
        else if (c >= 65 && c <= 90)
        {
            int j = c + 13;
            if (j > 90) j -= 26;
            buffer[i] = (char)j;
        }
        else
        {
            buffer[i] = (char)c;
        }
    }
    return new string(buffer);
}

I am sorry for any inconvenience, just trying to learn more about this pretty language :)

like image 943
RFerwerda Avatar asked Sep 11 '13 10:09

RFerwerda


1 Answers

What about this? I just happen to have this code lying around, it isn't pretty, but it does the job. Just to make sure: One liners are fun, but they usually do not improve readability and code maintainability... So I'd stick to your own solution :)

static string ROT13(string input)
{
    return !string.IsNullOrEmpty(input) ? new string (input.ToCharArray().Select(s =>  { return (char)(( s >= 97 && s <= 122 ) ? ( (s + 13 > 122 ) ? s - 13 : s + 13) : ( s >= 65 && s <= 90 ? (s + 13 > 90 ? s - 13 : s + 13) : s )); }).ToArray() ) : input;            
}

If you need more clarification, just ask.

like image 71
RvdV79 Avatar answered Sep 19 '22 18:09

RvdV79