Reversing Words in a String Using C#: Efficient String Manipulation Techniques
Learn two different C# methods for reversing the order of words in a string. This tutorial compares and contrasts these approaches, highlighting various string manipulation techniques and illustrating efficient string handling in C#.
Reversing Words in a String Using C#
This article presents two C# methods for reversing the order of words in a given string. These examples highlight different string manipulation techniques and illustrate how to efficiently handle string operations in C#.
Method 1: Using `Split()`, `Reverse()`, and `Join()`
This method uses built-in C# string manipulation functions for a concise solution. It's generally easier to understand and implement.
public static string ReverseWords(string input) {
string[] words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
return string.Join(" ", words);
}
This method splits the string into an array of words, reverses the array, and then joins the words back into a string.
Method 2: In-place Word Reversal
This method reverses the characters of each word in-place within the character array, then reverses the entire array to reverse the word order. This is a more advanced technique.
static void ReverseLetters(char[] str, int start, int end) {
// ... (code to reverse characters within a substring) ...
}
static char[] ReverseWordsInString(char[] inputString) {
int start = 0;
// ... (code to find word boundaries and reverse using ReverseLetters, then reverse entire string) ...
}