-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrawWordReverser.cs
More file actions
99 lines (81 loc) · 1.9 KB
/
rawWordReverser.cs
File metadata and controls
99 lines (81 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
public class MyStack
{
private const int MAX = 100;
public char[] _stack = new char[MAX];
public int _top = 0;
private bool IsFull()
{
return _top == MAX;
}
private bool IsEmpty()
{
return _top == 0;
}
public void Push(char input)
{
if (IsFull())
{
Console.WriteLine("Stack is full");
return;
}
_stack[_top++] = input;
}
public char Pop()
{
if (IsEmpty())
{
Console.WriteLine("Stack is empty");
return '\0';
}
return _stack[--_top];
}
}
public class WordReverser
{
public string ReverseWords(string input, MyStack stack)
{
string result = "";
for (int i = 0; i < input.Length; i++)
{
if (input[i] != ' ')
stack.Push(input[i]);
else
{
while (stack._top > 0)
result += stack.Pop();
result += ' ';
}
}
while (stack._top > 0)
result += stack.Pop();
return result;
}
}
public class Program
{
public static void Main(string[] args)
{
Console.Clear();
// Start of the program
MyStack stack = new MyStack();
WordReverser wordReverser = new WordReverser();
string result = "";
Console.WriteLine("Enter a sentence to reverse its words: ");
string? input;
do
{
Console.WriteLine("Please enter a valid sentence: ");
input = Console.ReadLine();
} while (string.IsNullOrEmpty(input));
try
{
result = wordReverser.ReverseWords(input, stack);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine($"The reversed sentence is: {result}");
}
}