Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think your question has been answered. My reply goes beyond the immediate question and more to the spirit of the exercise. I remember having this task many decades ago in college, when memory and mainframe (yikes!) processing time was at a premium. Our task was to reverse an array or string, which is an array of characters, without creating a 2nd array or string. The spirit of the exercise was to teach one to be mindful of available resources. </p> <p>In .NET, a string is an immutable object, so I must use a 2nd string. I wrote up 3 more examples to demonstrate different techniques that may be faster than your method, but which shouldn't be used to replace the built-in .NET Replace method. I'm partial to the last one.</p> <pre><code> // StringBuilder inserting at 0 index public static string Reverse2(string inputString) { var result = new StringBuilder(); foreach (char ch in inputString) { result.Insert(0, ch); } return result.ToString(); } // Process inputString backwards and append with StringBuilder public static string Reverse3(string inputString) { var result = new StringBuilder(); for (int i = inputString.Length - 1; i &gt;= 0; i--) { result.Append(inputString[i]); } return result.ToString(); } // Convert string to array and swap pertinent items public static string Reverse4(string inputString) { var chars = inputString.ToCharArray(); for (int i = 0; i &lt; (chars.Length/2); i++) { var temp = chars[i]; chars[i] = chars[chars.Length - 1 - i]; chars[chars.Length - 1 - i] = temp; } return new string(chars); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload