将字符串拆分为较小的字符串

时间:2014-09-02 10:03:06

标签: c# string foreach split

我有以下名单:

List<string> names = new List<string>();
names.Add("Tom Example");
names.Add("Ron Example");
names.Add("Peter Pavel Example");
names.Add("Pavel Ron Tom Example");

我想为列表的每个元素将字符串拆分为较小的字符串:

string firstName;
string firstInitial;
string lastName;
string lastInitial;
string secondName;
string secondInitial;

我想在循环中执行此方法因为我想在那些小字符串上做一些事情。如果我在字符串中有3个姓氏和姓氏,我希望只有第一个和第二个名字和姓氏。清关:

对于列表的最后一个元素,我希望得到这个结果:

string firstName == Pavel;
string firstInitial == P;
string lastName == Example;
string lastInitial == E;
string secondName == Ron;
string secondInitial == R;

我不知道如何实现此问题才能正常工作。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

我已为自己准备了以下解决方案:

public enum NameOptions
{
    FirstName = 1,
    MiddleName = 2,
    LastName = 4
};

然后扩展:

public static string SafeTokenPosition(this string @string, int index)
{
    if (string.IsNullOrEmpty(@string))
    {
        return string.Empty;
    }

    var tokens = @string.Split(new[] { " " }, 
                               StringSplitOptions.RemoveEmptyEntries);
    return index >= tokens.Length ? string.Empty : tokens[index];
}

private static string ResolveLastName(string name)
{
    if (string.IsNullOrWhiteSpace(name))
    {
        return string.Empty;
    }

    var tokens = name.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

    switch (tokens.Length)
    {
        case 2:
            return tokens[1];
        case 3:
            return tokens[2];
        default:
            return string.Empty;
    }
}

private static string ResolveMiddleName(string name)
{
    if (string.IsNullOrWhiteSpace(name))
    {
        return string.Empty;
    }

    var tokens = name.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

    switch (tokens.Length)
    {
        // ex. John Pablo Kowalsky
        case 3:
            return tokens[1];
        default:
            return string.Empty;
    }
}

private static string ResolveFirstName(string name)
{
    return name.SafeTokenPosition(0);
}

最后的延期:

public static string ExtractName(this string @string, NameOptions nameOptions)
{

    switch (nameOptions)
    {
        case NameOptions.FirstName:
            return ResolveFirstName(@string);
        case NameOptions.MiddleName:
            return ResolveMiddleName(@string);
        case NameOptions.LastName:
            return ResolveLastName(@string);
        default:
            throw new NotSupportedException("Name " + nameOptions + " is not supported.");
    }
}

用法:

var firstName = "John Sample".ExtractName(NameOptions.FirstName);

应该很容易扩展以处理首字母和两秒名称。