Deal with it or don't

Partition a string

This was started by another guy at work.
We needed to break a string up into fixed-width lines. This does that and returns an IEnumerable containing the lines.

public static IEnumerable<string> Partition(this string toPartition, int size)
	if (toPartition == null)
		throw new ArgumentNullException("toPartition");
	if (string.IsNullOrEmpty(toPartition) || size == 0)
		return new []{toPartition};
	if (size < 0)
		throw new ArgumentOutOfRangeException("size", size, "size must be non-negative");
	return toPartition
		.Select((character, index) => new {index, character})
		.GroupBy(p => p.index/size,
		      (x, anons) => anons.Aggregate(new StringBuilder(size), (builder, anon) => builder.Append(anon.character)).ToString());

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: