Click here to Skip to main content
15,886,797 members
Articles / Programming Languages / C#
Tip/Trick

CharRange: An Efficient Value Type for Ranges of Characters

Rate me:
Please Sign up or sign in to vote.
3.17/5 (6 votes)
9 Jan 2020MIT 4.3K   70   1  
Enumerate store and retrieve characters as sets of ranges using this efficient struct

Introduction

I use character ranges in my regular expression projects but they are obviously useful in many other situations. In fact, I'm somewhat surprised there isn't some sort of Range<T> struct in .NET with language support behind it. The reason CharRange isn't generic is because many of its operations are character specific.

Using this Mess

CharRange works like many other value types in that it uses value equality semantics and is comparable and equatable. However, it also implements enumeration and indexing.

C#
var test = "abcdlmnorstuvwxz";
// get a list of ranges for the above
var ranges = CharRange.GetRanges(test);
// write them out (looks like regex)
Console.Write("[");
foreach (var range in ranges)
    Console.Write(range);
Console.WriteLine("]");
// enumerate the characters in the ranges
Console.Write("ranges chars: ");
foreach (char ch in CharRange.ExpandRanges(ranges))
    Console.Write(ch);
Console.WriteLine();
// get a packed string - each char pair is one range
Console.WriteLine("Packed string: " + CharRange.ToPackedString(ranges));
// write out the inverted set of ranges (will look ugly in the console)
Console.Write("[");
foreach (var range in CharRange.NotRanges(ranges))
    Console.Write(range);
Console.WriteLine("]");
// range [a-x]
var a2x = new CharRange('a', 'x');
Console.WriteLine("[{0}]: Length = {1}", a2x, a2x.Length);
// indexing into the range to get the character at the index
Console.WriteLine("a2x[2] = " + a2x[2]);
// enumerate the characters in the range
Console.Write("a2x chars: ");
foreach (var ch in a2x)
    Console.Write(ch);
Console.WriteLine();

And that's all, kids. All the members are doc commented as well.

History

  • 9th January, 2020 - Initial submission

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United States United States
Just a shiny lil monster. Casts spells in C++. Mostly harmless.

Comments and Discussions

 
-- There are no messages in this forum --