C# byte[] 分割

wolf_Knight 2010-03-18 02:42:40
假如有这一个byte[]数组 byte[] tm = new byte[] { 94, 1, 2, 3, 94, 2, 3, 4, 5, 94, 3, 4};
然后以94作为分割,如上面,分成3个byte[];除了用Foreach这样循环来判断外,还有其他便捷的方法吗?谢谢!
...全文
1778 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
wolf_Knight 2010-03-24
  • 打赏
  • 举报
回复
结贴结贴,谢谢大家,虽然各位提供的代码还没有验证!
机器人 2010-03-19
  • 打赏
  • 举报
回复
转为ASCII字符串,再用字符串Split。不过得保证Byte中存放的是ASCII码范围内的Byte。


Encoding ascii = Encoding.ASCII;
byte[] tm = new byte[] { 94, 1, 2, 3, 94, 122, 24, 4, 5, 94, 3, 4 };
string target = ascii.GetString(tm);
char[] splitter = ascii.GetChars(new byte[] { 94 });

List<byte[]> result1 = new List<byte[]>();

string[] result = target.Split(splitter);
foreach (var str in result)
{
result1.Add(ascii.GetBytes(str));
}
cacaca6 2010-03-19
  • 打赏
  • 举报
回复
how can you guys' replay has colorful words? how to do that?
cacaca6 2010-03-19
  • 打赏
  • 举报
回复
I wrote a generic method to split any IEnumerable<> things, like this

public static List<List<T>> GenericSplit<T>(this IEnumerable<T> source, Predicate<T> criteria)
{
return source.Aggregate(new List<List<T>>(), (container, item) =>
{
if (container.Count == 0 || criteria(item))
container.Add(new List<T>());
else
container.Last().Add(item);
return container;
});
}

here is my article about it

http://topic.csdn.net/u/20100319/02/d201a60f-401a-4d3e-b094-ecd8486a5939.html?93067
kkandkkg 2010-03-19
  • 打赏
  • 举报
回复
写个方法就行。
Justin-Liu 2010-03-18
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 sp1234 的回复:]
其实只要一句话就搞定了。

C# code
var result = tm.Aggregate(new List<List<byte>>(), (container, x) =>
{
if (container.Count == 0 || x == 94)
container.Add(new List<byte>());
……
[/Quote]
继续受教
whowhen21 2010-03-18
  • 打赏
  • 举报
回复
( ⊙ o ⊙ )啊!,楼上不简单的人物啊
  • 打赏
  • 举报
回复
但是代码却是非常更加罗嗦 --> 但是代码却是非常诡异并且不是一般地罗嗦


楼主不经意间帮我出了一道今后面试程序员的小题目。
  • 打赏
  • 举报
回复
微软的风格可以用“追求一句话解决问题”来总结。而传统的java,则追求把简单的一东西写成一本厚厚的书并且冠名为模式,但是代码却是非常更加罗嗦。
  • 打赏
  • 举报
回复
其实只要一句话就搞定了。
var result = tm.Aggregate(new List<List<byte>>(), (container, x) =>
{
if (container.Count == 0 || x == 94)
container.Add(new List<byte>());
else
container.Last().Add(x);
return container;
})
.Select(lst => lst.ToArray());


以后开发,不懂Linq俺就不带他玩了。
myrroom 2010-03-18
  • 打赏
  • 举报
回复
把它变成string用string的XXX方法,哈哈不知道可行不
flyerwing 2010-03-18
  • 打赏
  • 举报
回复
copyto(array[])
这样不行吗
wolf_Knight 2010-03-18
  • 打赏
  • 举报
回复
UPUPUPUPUPUPUIP
wanghui0380 2010-03-18
  • 打赏
  • 举报
回复
没啥好方法的,题目总归了去就是 创建 集合的投影,所以循环是必须的
lexfu 2010-03-18
  • 打赏
  • 举报
回复
不用Foreach,也可以用堆栈试试,但是效率和实现复杂度方面就。。。。
兔子-顾问 2010-03-18
  • 打赏
  • 举报
回复
只能indexof然后自己截取。
cyx1225 2010-03-18
  • 打赏
  • 举报
回复
方法是有…只是不见得比它简便…
koukoujiayi 2010-03-18
  • 打赏
  • 举报
回复
的确!貌似没有!
menglingjun 2010-03-18
  • 打赏
  • 举报
回复
很遗憾。。貌似没有!

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧