在最后一个空格后拆分一个字符串

时间:2016-07-01 05:47:52

标签: c# c#-4.0

我创建了一个同步到数据库的程序,它接收名称,所以我想在最后一个“空格”之后将解析后的字符串拆分为2个字符串。

e.g。将“John Doe Jackson”这个名字分成: 约翰·多伊和杰克逊

到目前为止我做了什么,我得到了姓氏:

     public static string getLastName(string fullname)
    {
        string lastName = fullname.Split(' ').LastOrDefault();
        Console.WriteLine(lastName);
        return lastName;
    }

    public static string getFirstName(string fullname)
    {
        var parts = fullname.Split(' ');
        var lastName = parts.LastOrDefault();
        var firstName = string.Join(" ", parts.Take(parts.Length - 1));
        return firstName;
    }

如何返回字符串的其余部分,所以我有类似的东西:

  

firstName:John Doe

     

lastName:杰克逊

编辑:通过这样做来实现它,不是最干净的方式,但它完成了工作!

[  
   {  
      "order_id":34,
      "user_id":17,
      "sum":65000,
      "month":"May"
   },
   {  
      "order_id":32,
      "user_id":19,
      "sum":15000,
      "month":"July"
   },
   {  
      "order_id":29,
      "user_id":1,
      "sum":20000,
      "month":"April"
   }
]

5 个答案:

答案 0 :(得分:5)

您可以尝试这样的事情:

var parts = fullname.Split(' ');
var lastName = parts.LastOrDefault();
var firstName = string.Join(" ",parts.Take(parts.Length-1));

答案 1 :(得分:3)

我会这样做:

var lastSpaceIndex = fullName.LastIndexOf(' ');
var firstName = fullName.Substring(0, lastSpaceIndex);
var lastName = fullName.Substring(lastSpaceIndex+1);

See it in action here

答案 2 :(得分:1)

您可以使用string.Join

public static string getFirstName(string fullname)
{
    return string.join(" ",fullname.Split(' ').Take(fullname.Split(' ').Count()-1));

}

答案 3 :(得分:0)

string name = "John Doe Jackson";
var names = name.Split(' ');
string firstname = names[0] + " " + names[1];
string lastname = names[2];

答案 4 :(得分:0)

另一个基于接受答案的版本,但保护字符串为null / empty,并且在fullName中没有空格的情况下,将输入保留为firstName

        if (string.IsNullOrWhiteSpace(fullName)) return new KeyValuePair<string, string>(string.Empty, string.Empty);

        var parts = fullName.Trim().Split(' ');
        if (parts.Length == 1) return new KeyValuePair<string, string>(parts[0], string.Empty);

        var firstName = string.Join(" ", parts.Take(parts.Length - 1));
        var lastName = parts.LastOrDefault();

        return new KeyValuePair<string, string>(firstName, lastName);