8

I currently have the following code:

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

Input string user can be in one of two formats:

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

Whats the most elegant way in C# to convert either one of these strings to:

USER@DOMAIN
general exception
  • 4,202
  • 9
  • 54
  • 82

5 Answers5

7

Not sure you would call this most elegant:

string[] parts = user.Split(new string[] {"/"},
                            StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}@{1}", parts[1], parts[0]);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

How about this:

        string user = @"DOMAIN//USER";
        Regex pattern = new Regex("[/]+");
        var sp = pattern.Split(user);
        user = sp[1] + "@" + sp[0];
        Console.WriteLine(user);
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
2

A variation on Oded's answer might use Array.Reverse:

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

Alternatively, could use linq (based on here):

return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
       .Aggregate((current, next) => next + "@" + current);
Community
  • 1
  • 1
Jon Egerton
  • 40,401
  • 11
  • 97
  • 129
0

You may try this:

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

For the sake of adding another option, here it is:

string user = @"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "@" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));
StoriKnow
  • 5,738
  • 6
  • 37
  • 46