In C#, there are several ways to reverse a string. One of the simplest and most straightforward methods is to use the Array.Reverse
method in conjunction with the ToCharArray
method of the string.
Here is an example:
using System; namespace ReverseString { class Program { static void Main(string[] args) { Console.WriteLine(ReverseString("Hello World!")); } static string ReverseString(string input) { char[] charArray = input.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } } }
This program takes a string as input and returns the reversed string. The ToCharArray
method converts the string into an array of characters and Array.Reverse
reverses the elements in the array. Finally, the reversed character array is converted back into a string using the new string
constructor.
Output for Reverse String
!dlroW olleH
Unit test cases for Reverse String in C#
You can add unit tests to your code to ensure that your ReverseString
method is working correctly. Here is an example using the Assert
class from the Microsoft.VisualStudio.TestTools.UnitTesting
namespace:
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace ReverseString.Tests { [TestClass] public class ReverseStringTests { [TestMethod] public void ReverseString_WithHelloWorld_ReturnsDLROWOLLEH() { // Arrange string input = "Hello World"; // Act string result = ReverseString.Program.ReverseString(input); // Assert Assert.AreEqual("DLROW OLLEH", result); } [TestMethod] public void ReverseString_WithEmptyString_ReturnsEmptyString() { // Arrange string input = ""; // Act string result = ReverseString.Program.ReverseString(input); // Assert Assert.AreEqual("", result); } [TestMethod] public void ReverseString_WithSingleCharacter_ReturnsSameCharacter() { // Arrange string input = "a"; // Act string result = ReverseString.Program.ReverseString(input); // Assert Assert.AreEqual("a", result); } [TestMethod] public void ReverseString_WithNumbers_ReturnsReversedNumbers() { // Arrange string input = "12345"; // Act string result = ReverseString.Program.ReverseString(input); // Assert Assert.AreEqual("54321", result); } } }
These tests will check that your ReverseString method returns the correct result for different inputs, including an empty string, a string with a single character, a string with numbers, and a string with letters and spaces.
Conclusion
In conclusion, reversing a string in C# can be done easily using the Array.Reverse
method and the ToCharArray
method of the string. It’s always a good practice to add unit tests to your code to ensure that it’s working correctly and to catch any issues early on.
[…] C programming, C++ and C# became popular entries in this field. Despite their similar sounds, C, C++, and C# are all […]
[…] Guid struct is a value type in C# and has a default value of all zeroes, which represents an empty Guid. To […]