简体   繁体   中英

How to reverse a string without using built-in c# method

I want to know how to reverse a string in C# without using any .NET built-in methods.

My initial code:

Console.WriteLine("Please enter a string");
string myString = Console.ReadLine();  

The idea is to reverse the string named myString , which we are getting via the User's Console Input.

If you are trying to reverse a string that contains only English letters (I presume since your answer contains no methods to handle other letters), you could simplify your code by doing something like this:

private static string ReverseString(string myString)
{
    string reversedString = string.Empty;

    for (int i = myString.Length - 1; i >= 0 ; i--)
    {
        reversedString += myString[i];
    }

    return reversedString;
}

This method, obviously, doesn't contain any way to handle non-English letters, it is just a simplification of your answer.

We can convert the string to a char array and reverse the array. Given an array of size N, we only need to iterate in a loop for N/2 times while swapping the characters from the end of the array with the ones in the beginning. We can start from the beginning and ending characters, swap those and then move inwards with each iteration, until we reach the middle of the array.

    public static string Reverse(string input)
    {
        var inputArray = input.ToCharArray();
        var end = inputArray.Length / 2;

        for (int i = 0; i < end; i++)
        {
            var temp = inputArray[i];
            inputArray[i] = inputArray[inputArray.Length - i - 1];
            inputArray[inputArray.Length - i - 1] = temp;
        }

        var result = new string(inputArray);

        return result;
    }

convert it to a character array, reverse, convert to string. (that is how i would do it in java).

We can use the procedure below to reverse the String.

string myString = Console.ReadLine();
        char[] charStr = new char[str.Length];

        int k = charStr.Length - 1;
        for (int i=0;i<charStr.Length;i++)
        {
            int j = k;
            while (j>=0)
            {
                charStr[j] = str[i];
                j--;
            }
            k--;
        }

        foreach (char item in charStr)
        {
            Console.Write(item);
        }
        Console.WriteLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM