知识点
string
stirng.empty
- 表示空字符串。 此字段为只读。此字段的值为零长度字符串“”。
- string为引用数据类型。会在内存的栈和堆上分配存储空间。因此string.empty与“”都会在栈上保存一个地址,这个地址占4字节,指向内存堆中的某个长度为0的空间,这个空间保存的是string.empty的实际值。
- 区别于null,null 只在栈上分配了空间,在堆上没有分配
out
可以在两个上下文中使用 out 关键字:
- 作为 参数修饰符,通过引用而不是值将参数传递给方法。
- 在接口和委托的 泛型类型参数声明中 ,该声明指定类型参数是协变的。
- 当方法需要返回多个值时,关键字 out 特别有用,因为可以使用多个 out 参数。
public void main()
{
double radiusvalue = 3.92781;
//calculate the circumference and area of a circle, returning the results to main().
calculatecircumferenceandarea(radiusvalue, out double circumferenceresult, out var arearesult);
system.console.writeline($"circumference of a circle with a radius of {radiusvalue} is {circumferenceresult}.");
system.console.writeline($"area of a circle with a radius of {radiusvalue} is {arearesult}.");
console.readline();
}
//the calculation worker method.
public static void calculatecircumferenceandarea(double radius, out double circumference, out double area)
{
circumference = 2 * math.pi * radius;
area = math.pi * (radius * radius);
}
encoding
将字符串从一种编码转换为另一种编码,
编码(encoding):将 unicode 字符转换为字节序列的过程。
解码(decoding):将字节序列转换回 unicode 字符的过程。
方法
- getencoding。返回指定代码页的编码。属于编码过程
//返回与指定代码页名称关联的编码。
//encoding.getencoding(string)
using system;
using system.text;
public class samplesencoding {
public static void main() {
// get a utf-32 encoding by codepage.
encoding e1 = encoding.getencoding( 12000 );
// get a utf-32 encoding by name.
encoding e2 = encoding.getencoding( "utf-32" );
// check their equality.
console.writeline( "e1 equals e2? {0}", e1.equals( e2 ) );
}
}
/*
this code produces the following output.
e1 equals e2? true
*/
编码表

常用编码格式:

- getbytes
在派生类中重写时,将一组字符编码为一个字节序列。属于解码过程
//getbytes(char[]) //在派生类中重写时,将指定字符数组中的所有字符编码为一个字节序列。
字符串转换为数组
字符串可以理解为在字符数组。所以对手winform控件textbox的text值,也可以作为字符数组,
if(textbox1.text!="")
{
string chars_stra = "hello";
string chars_strb=string.empty;
char[] txtchars01 = new char[10];
char[] txtchars02 = new char[10];
for (int i=0;i<textbox1.text.length;i++)
{
txtchars01[i] =textbox1.text[i];
}
for(int j= 0; j< chars_stra.length; j++)
{
txtchars02[j] = chars_stra[j];
chars_strb += txtchars02[j];
}
}
代码

private void btn_toascii_click(object sender, eventargs e)
{
if(txt_char.text!=string.empty)
{
if(encoding.getencoding("unicode").getbytes(new char[] { txt_char.text[0] })[1]==0)
{
txt_ascii.text = encoding.getencoding("unicode").getbytes(txt_char.text)[0].tostring();
}
else
{
txt_ascii.text = string.empty;
messagebox.show("请输入字母!", "提示!");
}
}
}
private void btn_tochar_click(object sender, eventargs e)
{
if(txt_ascii2.text!=string.empty)
{
int p_int_num;//定义整型局部变量
if(int.tryparse(txt_ascii2.text,out p_int_num))
{
txt_char2.text = ((char)p_int_num).tostring();
}
else
{
messagebox.show("请输入正确ascii码值", "错误");
}
}
}
到此这篇关于c#实现ascii和字符串相互转换的代码示例的文章就介绍到这了,更多相关c# ascii和字符串互转内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论