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
4

5 回答 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]);
于 2012-08-03T14:03:09.757 回答
2

这个怎么样:

        string user = @"DOMAIN//USER";
        Regex pattern = new Regex("[/]+");
        var sp = pattern.Split(user);
        user = sp[1] + "@" + sp[0];
        Console.WriteLine(user);
于 2012-08-03T14:08:42.860 回答
2

Oded 答案的变体可能会使用Array.Reverse

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

或者,可以使用 linq(基于此处):

return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
       .Aggregate((current, next) => next + "@" + current);
于 2012-08-03T14:14:54.993 回答
0

你可以试试这个:

String[] parts = user.Split(new String[] {@"\", @"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}@{1}", parts[1], parts[0]);
于 2012-08-03T14:16:50.327 回答
0

为了添加另一个选项,这里是:

string user = @"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "@" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));
于 2012-08-03T14:18:36.597 回答