学完这个类没感到它会有什么用处, 同样的操作都不如在 string 类里方便, 还要 using System.Globalization;
主要成员:
/* 静态方法 */
StringInfo.GetNextTextElement(); //获取指定元素, 默认是获取第一个元素
StringInfo.GetTextElementEnumerator(); //获取枚举器
StringInfo.ParseCombiningCharacters(); //获取由序号组成的 int[]
/* 属性 */
LengthInTextElements; //元素数; 只读
String; //对象拥有的字符串; 可读写
/* 对象方法 */
SubstringByTextElements(); //截取字符串
构造函数及属性:
protected void Button1_Click(object sender, EventArgs e)
{
StringInfo sf = new StringInfo("abcdefg");
int n1 = sf.LengthInTextElements; //7
string s1 = sf.String; //abcdefg
TextBox1.Text = string.Concat(n1, "\n", s1);
}
protected void Button2_Click(object sender, EventArgs e)
{
StringInfo sf = new StringInfo();
int n1 = sf.LengthInTextElements; //0
string s1 = sf.String; //
sf.String = "abc";
int n2 = sf.LengthInTextElements; //3
string s2 = sf.String; //abc
TextBox1.Text = string.Concat(n1, "\n", s1, "\n" + n2, "\n", s2);
}
SubstringByTextElements() 方法:
protected void Button1_Click(object sender, EventArgs e)
{
StringInfo sf = new StringInfo("ABCDEFG");
string s1 = sf.SubstringByTextElements(2); //CDEFG
string s2 = sf.SubstringByTextElements(2, 3); //CDE
TextBox1.Text = s1 + "\n" + s2;
}
三个静态方法:
//StringInfo.GetNextTextElement()
protected void Button1_Click(object sender, EventArgs e)
{
string s1 = StringInfo.GetNextTextElement("ABCDEFG"); //A
string s2 = StringInfo.GetNextTextElement("ABCDEFG", 1); //B
TextBox1.Text = s1 + "\n" + s2;
}
//StringInfo.ParseCombiningCharacters()
protected void Button2_Click(object sender, EventArgs e)
{
int[] nArr = StringInfo.ParseCombiningCharacters("Asp.Net");
TextBox1.Text = string.Join(", ", nArr); //0, 1, 2, 3, 4, 5, 6
}
//StringInfo.GetTextElementEnumerator(); 使用 IEnumerator 需 using System.Collections;
protected void Button3_Click(object sender, EventArgs e)
{
string str = "ABCDEFG";
string s1, s2;
s1 = s2 = "";
IEnumerator e1 = StringInfo.GetTextElementEnumerator(str);
while (e1.MoveNext())
{
s1 += string.Format("{0} ", e1.Current); //A B C D E F G
}
IEnumerator e2 = StringInfo.GetTextElementEnumerator(str, 2);
while (e2.MoveNext())
{
s2 += string.Format("{0} ", e2.Current); //C D E F G
}
TextBox1.Text = s1 + "\n" + s2;
}