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,042
  • 8
  • 51
  • 81

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
  • 477,625
  • 97
  • 867
  • 998
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
  • 23,979
  • 6
  • 45
  • 64
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
  • 38,633
  • 11
  • 95
  • 128
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,497
  • 5
  • 36
  • 45