Change the position of words in a line

I have a string let say,

string temp1 = "25 10 2012" 

but i want it

 "2012 10 25" 

what would be the best way to do this. the format will always be like this.

+4
source share
6 answers

Looks like its date. You can parse a DateTime string using DateTime.ParseExact , and then use .ToString to return a formatted result.

 DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture); Console.Write(dt.ToString("yyyy MM dd")); 

You can use this DateTime object later in your code, as well as apply other formatting (if necessary)

+11
source

You can do this using the Split command, and then recombine the substrings:

 String[] subStrs = temp1.Split( ' ' ); String final = subStrs[2] + " " + subStrs[1] + " " + subStrs[0]; 
+1
source

So you want to break the words and reorder, you can use LINQ:

 var words = temp1.Split(' '); String newWord = string.Join(" ", words.Reverse()); 

or if you do not want to change all the words, but replace only the first and last word:

 String first = words.Last(); String last = words.First(); String newWord = first + " " + string.Join(" ", words.Skip(1).Take(words.Length - 2)) + " " + last; 
+1
source

try this split line and inverse array and this will work for a string of any length ...

 string[] myArray = temp1.Split(' '); Array.Reverse( myArray ); string reverse =string.Join(" ", myArray ); 
+1
source

You can use RegEx or split the string and return in reverse order.

 string s = "2012 10 25"; string[] tokens = s.Split(' '); Array.Reverse(tokens); string final = string.Join(" ", tokens); 
0
source

If your line always has 10 characters (with spaces), you can do the following:

 string str = "26 10 2012" str = str.Substring(6, 4) + " " + str.Substring(3, 2) + " " + str.Substring(0, 2) 
0
source

Source: https://habr.com/ru/post/1442033/


All Articles