Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How to Reverse the Order Of Words In A String
WhatsApp
Sanjit Kumar Singh
5y
36
k
0
6
25
Blog
WordReverse.zip
Introduction
In this blog, I am going to explain the program to reverse the order of words in a string.
Software Requirements
C# 3.0 or higher,
Visual Studio or Notepad
Example
Original Text: Singh Sanjit
Reversed order of words: Sanjit Singh
Program
using
System;
namespace
WordReverse {
public
static
class
Extension {
// This method will be treated as an extension and Static based on the way of call
public
static
string
[] ReverseWord(
this
string
[] strArray) {
if
(strArray
is
null
) {
throw
new
ArgumentNullException(nameof(strArray));
}
string
temp;
int
j = strArray.Length - 1;
for
(
int
i = 0; i < j; i++) {
temp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = temp;
j--;
}
return
strArray;
}
}
class
Program {
static
void
Main() {
Console.WriteLine(
"(Input is Optional and Default value will be 'Community of Software and Data Developers'"
);
Console.WriteLine(
"Enter your data to Reverse otherwise just Hit Enter"
);
var sampleText = Console.ReadLine();
if
(
string
.IsNullOrEmpty(sampleText))
sampleText =
"Community of Software and Data Developers"
;
Console.WriteLine(
"======================================================="
);
Console.WriteLine($
"Original Text : {sampleText}"
);
Console.WriteLine(
"======================================================="
);
Console.Write($
"Reversed order of words (Static Method): "
);
DisplayArrayValues(Extension.ReverseWord(sampleText.Split(
' '
)));
Console.WriteLine(
"======================================================"
);
Console.Write($
"Reversed order of words (Extension Method): "
);
DisplayArrayValues(sampleText.Split(
' '
).ReverseWord());
Console.ReadLine();
}
static
void
DisplayArrayValues(
string
[] strArray) {
if
(strArray
is
null
) {
throw
new
ArgumentNullException(nameof(strArray));
}
for
(
int
i = 0; i < strArray.Length; i++)
Console.Write(strArray[i] +
" "
);
Console.WriteLine();
}
}
}
Now run the code.
If the User does not enter anything, then the default value will be "https://www.c-sharpcorner.com." The following example is without input.
If User enters "power is Knowledge" it should look like the following:
Thank you so much for reading my blog.
Reverse Order Of Words In A String
string reverse
reverse string
People also reading
Membership not found