ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Reverse Words in a String

C#

Goal -- WPM

Ready
Exercise Algorithm Area
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class StringReverser
6{
7// Reverses the order of words in a given string.
8// Words are separated by one or more spaces.
9// Leading and trailing spaces are removed, and multiple spaces between words are reduced to a single space.
10public static string ReverseWords(string s)
11{
12// Handle null or empty input string.
13if (string.IsNullOrWhiteSpace(s))
14{
15return "";
16}
17
18// Split the string by spaces. The StringSplitOptions.RemoveEmptyEntries
19// option handles multiple spaces between words and leading/trailing spaces.
20string[] words = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
21
22// Reverse the array of words.
23Array.Reverse(words);
24
25// Join the reversed words back into a single string with single spaces.
26return string.Join(" ", words);
27}
28
29public static void Main(string[] args)
30{
31string testString1 = "the sky is blue";
32string reversed1 = ReverseWords(testString1);
33Console.WriteLine($"Original: '{testString1}'\nReversed: '{reversed1}'"); // Expected: "blue is sky the"
34
35string testString2 = " hello world ";
36string reversed2 = ReverseWords(testString2);
37Console.WriteLine($"Original: '{testString2}'\nReversed: '{reversed2}'"); // Expected: "world hello"
38
39string testString3 = "a good example";
40string reversed3 = ReverseWords(testString3);
41Console.WriteLine($"Original: '{testString3}'\nReversed: '{reversed3}'"); // Expected: "example good a"
42
43string testString4 = "singleword";
44string reversed4 = ReverseWords(testString4);
45Console.WriteLine($"Original: '{testString4}'\nReversed: '{reversed4}'"); // Expected: "singleword"
46
47string emptyString = " ";
48string reversed5 = ReverseWords(emptyString);
49Console.WriteLine($"Original: '{emptyString}'\nReversed: '{reversed5}'"); // Expected: ""
50
51string nullString = null;
52string reversed6 = ReverseWords(nullString);
53Console.WriteLine($"Original: null\nReversed: '{reversed6}'"); // Expected: ""
54}
55}
Algorithm description viewbox

Reverse Words in a String

Algorithm description:

This C# function reverses the order of words in a given string. It intelligently handles cases with multiple spaces between words, as well as leading and trailing spaces, ensuring the output string has words separated by single spaces and no extraneous whitespace. This is a common string manipulation task used in text processing, command-line interfaces, or preparing user input for further analysis.

Algorithm explanation:

The `ReverseWords` function takes a string `s` and returns a new string with the words in reversed order. First, it checks for null or whitespace input using `string.IsNullOrWhiteSpace(s)`, returning an empty string if true. This handles edge cases like null, empty, or strings containing only spaces. The core logic involves splitting the input string into an array of words using `s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)`. The `RemoveEmptyEntries` option is crucial as it automatically discards any empty strings that result from multiple spaces or leading/trailing spaces, ensuring only actual words are captured. After splitting, `Array.Reverse(words)` is called to reverse the order of elements in the `words` array. Finally, `string.Join(" ", words)` concatenates the reversed words back into a single string, using a single space as the delimiter. The time complexity is dominated by the split and join operations, which are typically O(n), where n is the length of the string. The `Array.Reverse` operation is O(k), where k is the number of words. Thus, the overall time complexity is O(n). The space complexity is O(n) in the worst case, as a new string and an array of words are created, potentially storing all characters of the original string.

Pseudocode:

function ReverseWords(s):
  if s is null or whitespace:
    return ""

  words = split s by space, removing empty entries
  reverse the order of elements in the words array
  result = join elements of words array with a single space

  return result