c# - 是否可以在一行中编写 ROT13?

标签 c# encryption rot13

我有以下代码,我希望将其视为单行代码。但是,由于我是 C# 的新手,我目前不知道如何执行此操作...

代码:

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);
}

对于给您带来的不便,我深表歉意,我只是想了解更多关于这门漂亮语言的知识:)

最佳答案

这个呢? 我只是碰巧有这段代码,它不漂亮,但它完成了工作。 只是为了确保:一个衬里很有趣,但它们通常不会提高可读性和代码可维护性......所以我会坚持使用你自己的解决方案:)

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;            
}

如果您需要更多说明,请询问。

刚刚也添加了这个,为更漂亮的单行本的爱好者(也更好读):-)

 public static string Rot13(string input) => Regex.Replace(input, "[a-zA-Z]", new MatchEvaluator(c => ((char)(c.Value[0] + (Char.ToLower(c.Value[0]) >= 'n' ? -13 : 13))).ToString()));

关于c# - 是否可以在一行中编写 ROT13?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18739091/

相关文章:

java - 如何使密文字符与明文字符相同?

python - 为什么我必须创建一个空字符串来替换字符串中的所有字符?

C# 窗体 : Full Screen UserControl

android - 使用 Android 指纹时出现问题 : IV required when decrypting. 使用 IvParameterSpec 或 AlgorithmParameters 提供

c# - 多层解决方案中的 StructureMap

Java AES提高安全性,keystring需要多长

c - 为什么我无法使用 PEM_read_RSAPublicKey 读取 openssl 生成的 RSA 公钥?

python - 为什么 python-3.x 删除了 ROT-13 作为编码?

c# - System.Uri 在 .NET 4.5+ 中删除 Unicode RLM(从右到左标记;U+200F)字符

c# - F# 使用非托管 dll 函数