gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:03:06 25 4
gpt4 key购买 nike

我有以下代码,我希望将其视为单行代码。但是,由于我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com