- A+
所属分类:.NET技术
字符串处理
大小写转换
ToUpper和ToLower方法
string str="ASDFGHhjkl"; str.ToUpper()//全部转大写 str.ToLower();//全部转小写
字母转ASCII码
//字母转ASCII string str="A"; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding encoding = Encoding.GetEncoding("unicode"); byte [] by=encoding.GetBytes(str); string ASCII=by[0].ToString(); //ASCII转字母 int x; string lettr=((char)x).ToString();
Encoding n.[计]编码 v. [计]编码(encode 的 ing 形式)
运行.NET Core或.NET 5+的应用程序,这些版本的.NET不包括所有的编码。你需要注册System.Text.Encoding.CodePages包,然后使用Encoding.GetEncoding方法。
//注册System.Text.Encoding.CodePages包 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
汉字转区位码
汉字转区位码
public string GetCode(string Chinese) { ////注册System.Text.Encoding.CodePages包 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding gb2312 = Encoding.GetEncoding("GB2312"); byte[] bytes = gb2312.GetBytes(Chinese); // 提取区位码 int front = bytes[0] - 160; int back = bytes[1] - 160; return front.ToString() + back.ToString(); }
区位码转汉字
public string GetChinese(string code) { ////注册System.Text.Encoding.CodePages包 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding gb2312 = Encoding.GetEncoding("GB2312"); int front = Convert.ToInt32(code.Substring(0, 2))+160; int back = Convert.ToInt32(code.Substring(2, 2))+160; byte[] bytes = new byte[] { (byte)front, (byte)back }; return gb2312.GetString(bytes); }
这里用到了一个Substring()函数,用法如下
Substring()函数
string str = "Hello, World!"; string sub1 = str.Substring(7); // 返回 "World!" string sub2 = str.Substring(7, 5); // 返回 "World" string sub2 = str.Substring(7, 4); //返回"Worl"
string Substring(int startIndex): 这种形式返回一个新的字符串,该字符串从当前字符串的指定索引开始一直到尾部。索引是基于0的,所以如果 startIndex 是0,那么它将返回原始字符串。
string Substring(int startIndex, int length): 这种形式返回一个新的字符串,该字符串从当前字符串的指定索引开始,并且长度为指定的长度。如果 startIndex 是0,那么它将返回一个长度为 length 的字符串,该字符串的内容与原始字符串的前 length 个字符相同。