C# Program To Reverse Words In A Given String

Software development often requires the ability to invert the sequence of words in a string. This task can be accomplished systematically in the C# programming language. An innovative resolution to this challenge is illustrated in the provided C# script. The script efficiently reverses the word order in a specified string by leveraging fundamental string manipulation methods and the array capabilities of C#. Individuals can enhance their understanding of array manipulation, reconstructing strings, and segmenting strings into substrings to achieve intended outcomes by studying this script. This software exemplifies the effectiveness of C# in managing such operations and offers a practical demonstration of string manipulation principles.

Example Code:

Let's consider a C# demonstration to showcase the process of reversing words within a provided string.

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        // Prompt the user to enter a string
        Console.WriteLine("Enter a string:");
        string inputString = Console.ReadLine();

        // Call the method to reverse words in the string
        string reversedString = ReverseWords(inputString);

        // Display the reversed string
        Console.WriteLine("Reversed string:");
        Console.WriteLine(reversedString);
    }

    // Method to reverse words in a given string
    static string ReverseWords(string input)
    {
        // Split the input string into an array of words
        string[] words = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        // Reverse the array of words
        Array.Reverse(words);

        // Join the reversed words back into a string
        string reversedString = string.Join(" ", words);

        return reversedString;
    }
}

Output:

Output

Enter a string:
Hello everyone
Reversed string:
everyone Hello
Enter a string:
I love programming
Reversed string:
programming love I

Explanation:

  • In this example, we first include the System namespace for input/output operations.
  • The program's entry point is defined by a Main method in a Program class.
  • Next, we use WriteLine inside the Main method to ask the user to enter a string. Use Console.ReadLine method to read the input string.
  • After that, the words in the string are reversed by invoking the ReverseWords function and providing the input string as an argument.
  • When a string is supplied, the ReverseWords function reverses the order of the string's words.
  • Split is used inside the ReverseWords method to split the input string into an array of words. We employ a space character as the delimiter to divide the string into words.
  • After that, we reverse the word reverse using Array.
  • Finally, we use string to rejoin the reversed words into a Join , separating words with a space character.
  • The console is used to show the reversed string to the user when it is returned to the Main write Line .
  • Example 2:

Let's consider a different C# instance to demonstrate the process of reversing words within a provided string.

Example

using System;

class Program
{
    // Reverse the letters of the word
    static void ReverseLetters(char[] str, int start, int end)
    {
        char temp;

        while (start <= end)
        {
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }

    // Function to reverse words
    static char[] ReverseWordsInString(char[] inputString)
    {
        int start = 0;
        for (int end = 0; end < inputString.Length; end++)
        {
            // If we encounter a space, we reverse the previous word
            if (inputString[end] == ' ')
            {
                ReverseLetters(inputString, start, end);
                start = end + 1;
            }
        }

        // Reverse the last word
        ReverseLetters(inputString, start, inputString.Length - 1);

        // Reverse the entire string
        ReverseLetters(inputString, 0, inputString.Length - 1);

        return inputString;
    }

    // Driver code
    public static void Main(string[] args)
    {
        string input = "This is a sample string";
        char[] charArray = ReverseWordsInString(input.ToCharArray());
        string reversedString = new string(charArray);
        Console.WriteLine("Reversed string: " + reversedString);
    }
}

Output:

Output

Reversed string: stringsample a is This

Conclusion:

In summary, the C# program offers a dependable method for inverting words within a specified string. It employs efficient algorithms to scan through the input string, identifying word boundaries by recognizing spaces. Upon encountering a space, it reverses the characters of the preceding word, ultimately flipping the entire string. By utilizing native functionalities like Split and Join along with personalized functions for character reversal, this program showcases the adaptability of C# in manipulating strings. The well-structured logic and clear variable names make the code easily comprehensible. This software serves as a practical demonstration of string manipulation techniques in C# and is applicable to various text-processing scenarios.

Input Required

This code uses input(). Please provide values below: