Reputation: 263
original String is "Hello World"
Output Should be "World Hello"
What is the optimized way to do it in c# ?
Please suggest me any existing link if i am missing
Upvotes: 0
Views: 1267
Reputation: 2992
char[] Delimiter = new char[] { ' ' }
string[] t = string.split("Hello Wordl", Delimiter)
int lenS = t.Count;
string result = "";
for(int x =t-1; t > -1; t--)
{
result += t[x] + " ";
}
//Used result now
Upvotes: -1
Reputation: 684
var s = "Hello world";
var result = String.Join(" ", s.Split(' ').Reverse()));
OR (better split below if you ar not sure of your data)
var s = "Hello world";
var result = String.Join(" ", Regex.Split(s, @"\s").Reverse());
Upvotes: 4
Reputation: 26209
static void Main(string[] args)
{
String str = "Hello World";
String[] strNames = str.Split(' ');
for(int i=strNames.Length-1;i>=0;i--)
Console.Write(strNames[i]+" ");
}
Upvotes: 0
Reputation: 313
Try This Code :
string value = "Hello world";
string firstvalue = value.Split(' ').First();
string secvalue = value.Split(' ').Last();
string value = secvalue + firstvalue;
Upvotes: 0
Reputation: 1529
I would split the sentence by the words (the space between them):
string[] words = helloString.Split(" ");
helloString = words[1] + " " + words[0];
You could optimise this to work with any sentence with any number of words by looping through words
from the last element to the first.
I've reassigned the new string back to helloString (the original) as I assume this is what you want based on the question.
Upvotes: 1