ReverseString, a C# interview-question

前端 未结 12 1849
予麋鹿
予麋鹿 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:04

    This method cuts the number of iterations in half. Rather than starting from the end, it starts from the beginning and swaps characters until it hits center. Had to convert the string to a char array because the indexer on a string has no setter.

        public string Reverse(String value)
        {
            if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
    
            char[] array = value.ToCharArray();
    
            for (int i = 0; i < value.Length / 2; i++)
            {
                char temp = array[i];
                array[i] = array[(array.Length - 1) - i];
                array[(array.Length - 1) - i] = temp;
            }
    
            return new string(array);
        }
    

提交回复
热议问题