分割字符串后获取最后四个单词

时间:2018-02-15 11:14:58

标签: c# .net

我有两个字符串如下

var str1 = '20180215.20150215.3.1.0.0';
var str2 = '20180215.3.1.0.0';

我需要在将这些字符串拆分后得到最后四个字。

var str1Arr = str1.split('.')

我需要的是获得最后四个单词3.1.0.0的通用方法。

由于

7 个答案:

答案 0 :(得分:7)

var lastFour = str1Arr.Reverse().Take(4).Reverse().ToArray();

答案 1 :(得分:2)

public static class SplitExtension
{
    public static string LastNItems(this string str, int nItem, char separator = '.')
    {
        return string.Join(separator.ToString(), str.Split(separator).Reverse().Take(nItem).Reverse());
    }

    public static string[] LastNItems(this string[] strArray, int nItem)
    {
        return strArray.Reverse().Take(nItem).Reverse().ToArray();
    }
}

这将使您能够

var str1 = "20180215.20150215.3.1.0.0";

var str1Last4 = str1.LastNItems(4); // "3.1.0.0"
var str1Last4Items = str1.Split('.').LastNItems(4); // ["3","1","0","0"]

或完成

var str1Last4Items = str1.LastNItems(4).Split('.'); // ["3","1","0","0"]

答案 2 :(得分:1)

您可以通过扩展方法使用它。

public static class CommonExtension
{
    public static List<string> LastNItem(this string str, int nItem, string separator = ".")
    {
        var splittedWords = str.Split(new [] { separator }, StringSplitOptions.None);
        var res = splittedWords.Reverse().Take(nItem).Reverse().ToList();

        return res;
    }
}

然后你可以随意调用它。

var str1 = "1.0.0";
var str2 = "20180215.3.1.0.0";

var str1Last4 = str1.LastNItem(4);
var str2Last4 = str2.LastNItem(4);

答案 3 :(得分:1)

为什么不只是Skip最高Length - 4项?

string str1 = "20180215.20150215.3.1.0.0";

string[] str1Arr = str1.Split('.');

var result = str1Arr
  .Skip(str1Arr.Length - 4)
  .ToArray(); // if you want an array materialization

即使str1Arr.Length < 4(在这种情况下将返回整个str1Arr副本),此代码也会执行此操作。如果您希望string作为result,则可以尝试Substring(不创建任何数组)

  string str1 = "20180215.20150215.3.1.0.0";
  string result = str1;
  int index = result.Length;

  for (int i = 0; i < 4; ++i) {
    index = str1.LastIndexOf('.', index - 1);

    if (index < 0)
      break;
  }

  result = index < 0 ? result : result.Substring(index + 1);

答案 4 :(得分:0)

这比双反向回答要快。

var str1 = "20180215.20150215.3.1.0.0";
var str2 = "20180215.3.1.0.0";

var words = str1.Split('.');
var toSkip =  words.Length - 4;
var result = string.Join(".", words.Skip(toSkip));

一些测试结果显示,它比双反转快一点。

比这个快10倍? 好了,避免内存分配和枚举。

以下是比较3种不同扩展方法进行10M迭代的结果:

双反:6463ms
split + skip:5269ms
直:492ms

void Main()
{
    var str1 = "20180215.20150215.3.1.0.0";

    var numIterations = 10000000;

    var timer = new Stopwatch();


    timer.Start();
    for (var i = 0; i < numIterations; i++)
    {
        str1.LastNItemsDoubleReverse(4);
    }
    timer.Stop();
    timer.ElapsedMilliseconds.Dump("double reverse");

    timer.Reset();
    timer.Start();
    for (var i = 0; i < numIterations; i++)
    {
        str1.LastNItemsSplitNSkip(4);
    }
    timer.Stop();
    timer.ElapsedMilliseconds.Dump("split + skip");

    timer.Reset();
    timer.Start();
    for (var i = 0; i < numIterations; i++)
    {
        str1.LastNItemsStraight(4);
    }
    timer.Stop();
    timer.ElapsedMilliseconds.Dump("straight");

}
public static class ext
{
    public static string LastNItemsDoubleReverse(this string str, int nItem, char separator = '.')
    {
        return string.Join(separator.ToString(), str.Split(separator).Reverse().Take(nItem).Reverse());
    }

    public static string LastNItemsSplitNSkip(this string str, int nItem, char separator = '.')
    {

        var words = str.Split(separator);
        var toSkip = words.Length - nItem;
        return string.Join($"{separator}", words.Skip(toSkip));
    }

    public static string LastNItemsStraight(this string str, int nItem, char separator = '.')
    {

        int j=1,i=str.Length-1;
        for (;i>=0 && j<nItem;i--){
            if(str[i]==separator) j++;
        }
        return str.Substring(i);

    }
}

答案 5 :(得分:0)

public static string GetLastFour(string str)
{
    string[] arr = str.Split('.');
    System.Text.StringBuilder lastFour = new System.Text.StringBuilder();
    if (arr.Length >= 4)
    {
        for (int k = arr.Length - 4; k < arr.Length; k++)
        {
            if (k == arr.Length - 1)
            {
                lastFour.Append(arr[k]);
            }
            else
            {
                lastFour.Append(arr[k] + ".");
            }
        }
    }

    return lastFour.ToString();
}

答案 6 :(得分:-1)

尝试以下方法:

List<string> GetLastFourWords()
{
   List<string> lastFour = new List<string>();

   try
   {
      string[] arr = str1.split('.');
      for(int i = 3; i >= 0; i-- )
      {
         lastFour.Add(arr[str1.length - 1 - i]);
      }
   }
   catch(Exception ex)
   {
   }

   return lastFour;
}