如何使用条件将数组中的项拆分为两个项?

时间:2016-06-17 08:25:17

标签: c# arrays

我上面有一个例子。

有类似的数组:

array[0] = TODO 06:15PMJoin Michael
array[1] = WakeUp
array[2] = Going to schools

我希望它变得像:

array[0] = TODO 06:15PM
array[1] = Join Michael
array[2] = WakeUp
array[3] = Going to schools

在此示例中,我将内容TODO 06:15PMJoin Michael拆分为新的两个项目。

这里有两个不同的问题:

如何创建在数组中创建新项目的角色?

我尝试使用我的代码:

var splitList = words.SelectMany(x => x.Contains("AM") || x.Contains("PM"))

但我不知道如何将文字AMPM拆分为arrays中的新项目。

2 个答案:

答案 0 :(得分:5)

您可以尝试查找AM / PM并获取子字符串:

  String[] array = new String[] {
    "TODO 06:15PMJoin Michael",
    "WakeUp",
    "Going to schools"
  };

  var result = array
    .SelectMany(line => {
        int p = line.IndexOf("AM");

        if (p >= 0)
          return new String[] { 
            line.Substring(0, p + "AM".Length), 
            line.Substring(p + "AM".Length) };

        p = line.IndexOf("PM");

        if (p >= 0)
          return new String[] { 
            line.Substring(0, p + "PM".Length), 
            line.Substring(p + "PM".Length) };

        return new String[] { line };
      }
    );
  //.ToArray(); // if you want to have array representation

  // Test
  Console.Write(String.Join(Environment.NewLine, result));

答案 1 :(得分:1)

你也可以试试这个:

string[] array = new string[] {"TODO 06:15PMJoin Michael", 
    "WakeUp", 
    "Going to schools"};

string[] SplitArray(string[] array)
{
    List<string> returnArray = new List<string>();

    foreach (string item in array)
    {
        int index = GetIndex(item);
        if (index >= 0)
        {
            string s1 = item.Substring(0, index + 2);
            string s2 = item.Substring(index + 2);
            returnArray.Add(s1);
            returnArray.Add(s2);
        }
        else
        {
            returnArray.Add(item);
        }
    }

    return returnArray.ToArray();
}

int GetIndex(string s)
{
    int index = GetIndexOf(s, "AM");

    if (index == -1)
    {
        index = GetIndexOf(s, "PM");
    }

    return index;
}

int GetIndexOf(string s, string delim)
{
    int index = -1;

    int tempIndex = 0;
    do
    {
        tempIndex = s.IndexOf(delim, tempIndex);
        if (tempIndex > 0)
        {
            if (char.IsDigit(s[tempIndex-1]))
            {
                index = tempIndex;
                break;
            }
        }
    }
    while(tempIndex >= 0);

    return index;
}