C # convert DOMAIN \ USER to USER @DOMAIN

I currently have the following code:

string user = @"DOMAIN\USER"; string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None); string user = parts[1] + "@" + parts[0]; 

The user input string can be in one of two formats:

 DOMAIN\USER DOMAIN\\USER (with a double slash) 

What is the most elegant way in C # to convert one of these lines to:

 USER@DOMAIN 
+7
source share
5 answers

Not sure if you would call it the most elegant:

 string[] parts = user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries); string user = string.Format("{0}@{1}", parts[1], parts[0]); 
+7
source

How about this:

  string user = @"DOMAIN//USER"; Regex pattern = new Regex("[/]+"); var sp = pattern.Split(user); user = sp[1] + "@" + sp[0]; Console.WriteLine(user); 
+2
source

The Oded answer option may use Array.Reverse :

 string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries); Array.Reverse(parts); return String.Join("@",parts); 

Alternatively, you can use linq (based on here ):

 return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries) .Aggregate((current, next) => next + "@" + current); 
+2
source

You can try the following:

 String[] parts = user.Split(new String[] {@"\", @"\\"}, StringSplitOptions.RemoveEmptyEntries); user = String.Format("{0}@{1}", parts[1], parts[0]); 
0
source

To add another option, follow these steps:

 string user = @"DOMAIN//USER"; string result = user.Substring(0, user.IndexOf("/")) + "@" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1)); 
0
source

All Articles