ReverseString, a C# interview-question

前端 未结 12 1868
予麋鹿
予麋鹿 2021-01-31 06:15

I had an interview question that asked me for my \'feedback\' on a piece of code a junior programmer wrote. They hinted there may be a problem and said it will be used heavily o

12条回答
  •  长发绾君心
    2021-01-31 07:09

    Most importantly? That will suck performance wise - it has to create lots of strings (one per character). The simplest way is something like:

    public static string Reverse(string sz) // ideal for an extension method
    {
        if (string.IsNullOrEmpty(sz) || sz.Length == 1) return sz;
        char[] chars = sz.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
    

提交回复
热议问题