Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Count with Letters

0.00/5 (No votes)
16 Jun 2007 1  
A way to use letters instead of numbers to count

Introduction

I had to write a "text tool" application a few days ago, and one of the requests was to "number" text lines with letters (like Microsoft Word does from bullets and numbering). Because I couldn't find an "already made" function for this, I had to do it myself. It's not difficult - this article is for beginner's (plus) level.

Background

To understand this function, all you need is to have basic knowledge of C# (to know the char type, the string type and to understand how to convert between these types).

Using the Code

This code is free. You can use and redistribute. You can improve it (because it is not perfect).

The code

The function is like this:

private string GetNext(string current) 
{return curent + 1; // the next value}

Let's say that current = "a", then, the return will be "b". If the current = "z", the return will be "aa". If current = "abcd" the return is "abce" and so on.

To do this, I need 2 auxiliary functions:

private char GetNextChar(char c)
{
	if (c < 'z')
		return (char)((int)c + 1);
	else 
		return 'a'; 
} 

and:

private string ReverseString(string str)
{
	StringBuilder sb = new StringBuilder();
	for (int i = str.Length - 1; i >= 0; i--)
		sb.Append(str[i]);
	return sb.ToString();
}

The ReverseString function is only because I feel more comfortable to work with the string from left to right.

The main function is:

private string GetNext(string curent)
{
	string next = "";
	int depl = 0;
	curent = ReverseString(curent);
	char curent_digit;

	curent_digit = GetNextChar(curent[0]);
	if (curent_digit < curent[0])
		depl = 1;
	else
		depl = 0;
	next = curent_digit.ToString();
            
	for (int i = 1; i < curent.Length; i++)
	{
		curent_digit = curent[i];
		if (depl != 0)
		{
			curent_digit = GetNextChar(curent[i]);
			if (curent_digit < curent[i])
				depl = 1;
			else
				depl = 0;
		}
	                
		next += curent_digit.ToString();
	
	}
	if (depl == 1)
		next += 'a'.ToString();
	return ReverseString(next);
} 

As an example of usage for this:

private void btnNext_Click(object sender, EventArgs e)
{
	string s = txtCurent.Text;
	StringBuilder tmp = new StringBuilder();
	for (int i = 0; i < 10000; i++)
	{
		s = GetNext(s);
		tmp.AppendLine(s);
	}
	lblLast.Text = s.ToString();
}

A form, with a button and a textbox (with multiline = true) to see the result.

History

  • 17th June, 2007: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here