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
1
  • 1
    You could do it with a Regex. I'll leave someone else to construct that regex though :) Commented Aug 3, 2012 at 14:06

5 Answers 5

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

@MAfifi - Not needed, not with RemoveEmptyEntries. Try it.
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);

1 Comment

Agh, that'll teach me from thinking I understand regexes for a while. +1
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);

Comments

0

You may try this:

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

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.