带字母的计数
一种使用字母而不是数字进行计数的方法。
引言
几天前我需要编写一个“文本工具”应用程序,其中一个请求是使用字母对文本行进行“编号”(就像 Microsoft Word 中的项目符号和编号一样)。由于我找不到为此目的“现成的”函数,我不得不自己编写。这并不难 - 这篇文章面向初学者(以及更高水平的人)。
背景
要理解这个函数,你只需要具备 C# 的基本知识(了解 char
类型、string
类型以及了解如何在这些类型之间转换)。
Using the Code
此代码是免费的。你可以使用和重新分发。你也可以改进它(因为它并不完美)。
代码
函数如下所示
private string GetNext(string current)
{return curent + 1; // the next value}
假设 current = "a"
,那么返回值将是 "b
"。如果 current = "z"
,返回值将是 "aa
"。如果 current = "abcd"
,返回值是 "abce
" 以此类推。
为此,我需要 2 个辅助函数
private char GetNextChar(char c)
{
if (c < 'z')
return (char)((int)c + 1);
else
return 'a';
}
和
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();
}
ReverseString
函数仅仅是因为我更习惯于从左到右处理 string
。
主要函数是
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);
}
作为此函数的用法示例
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();
}
一个窗体,包含一个按钮和一个文本框(multiline = true
)以查看结果。
历史
- 2007 年 6 月 17 日:初始发布