c# – 没有string的分裂字符串.Split

前端之家收集整理的这篇文章主要介绍了c# – 没有string的分裂字符串.Split前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在做一个家庭工作问题,不使用框架方法拆分字符串.

以下是我提出的工作代码.

我想知道如何改善O(n)的运行时间?

此外,欢迎任何改进建议.

  1. public static string[] split(string txt,char[] delim)
  2. {
  3. char[] text = txt.tocharArray();
  4. string[] result = new string[0];
  5. int count = 0;
  6. int i = 0;
  7. StringBuilder buff = new StringBuilder();
  8. while(i < text.Length)
  9. {
  10. bool found = false;
  11. foreach(char del in delim)
  12. {
  13. if(del == txt[i])
  14. {
  15. found = true;
  16. break;
  17. }
  18. }
  19. if(found)
  20. {
  21. count++;
  22. Array.Resize(ref result,count);
  23. result[count - 1] = buff.ToString();
  24. buff = new StringBuilder();
  25. }
  26. else
  27. {
  28. buff.Append(txt[i]);
  29. }
  30.  
  31. i++;
  32. }
  33.  
  34. if(buff.Length != 0)
  35. {
  36. count++;
  37. Array.Resize(ref result,count);
  38. result[count - 1] = buff.ToString();
  39. }
  40.  
  41. return(result);
  42. }

解决方法

我有一些更改会同时使这个函数更像C,并将运行时间减少到O(n):

1)你应该多次动态调整结果数组的大小,而不是动态地调整结果数组的大小,而应该创建足够的点来保存最大数量的字符串(你知道这个数字小于txt.Length),然后在最后一次调整它的大小.归还它.

2)不要使用StringBuilder组合你的结果,而是制作长度为txt.Length且索引变量为j的char [] buff并执行buff [j] = txt [i].

我认为你的功能应该是O(N).从技术上讲,它将是O(N * M),其中M是分隔符的数量.

编辑1:

这是一个改变,它将使O(N)O(M)而不是O(N * M):

您应该循环遍历ADVANCE中的分隔符并设置如下所示的数组,而不是循环遍历字符串中每个字符的分隔符:

  1. bool[] isDelimiter = new bool[128]; // increase size if you are allowing non-ascii
  2. foreach(char delim in isDelimiter)
  3. {
  4. isDelimiter[(int)char] = true;
  5. }

然后你可以使用这个数组在恒定时间内测试字符串的每个字符.

猜你在找的C#相关文章