超简单的C语言入门教程有哪些?

2026-05-08 21:143阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计335个文字,预计阅读时间需要2分钟。

超简单的C语言入门教程有哪些?

在常规情况下,我们直接使用 `string.length` 来获取字符串的长度。但是,对于汉字来说,每个汉字实际上由两个字节组成。因此,直接使用 `length` 属性会错误地计算字符串的长度。以下是一个获取字符串正确长度的示例代码:

csharpprivate void button1_Click(object sender, EventArgs e){ string chineseString=这是一段汉字测试字符串; int actualLength=chineseString.Length * 2; // 汉字长度为两个字节 Console.WriteLine(字符串的实际长度为: + actualLength);}

正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图:

所以应该用以下代码来获取长度:

private void button1_Click(object sender, EventArgs e) { string s = textBox1.Text; int i = GetLength(s); MessageBox.Show(i.ToString()); } public static int GetLength(string str) { if (str.Length == 0) return 0; ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; byte[] s = ascii.GetBytes(str); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } } return tempLen; }

运行结果如下图:

也可以用这个获取长度:

int i = System.Text.Encoding.Default.GetBytes(s).Length;

通过系统提供函数我们就可以获取中文的真实长度,是不是很简单

超简单的C语言入门教程有哪些?

本文共计335个文字,预计阅读时间需要2分钟。

超简单的C语言入门教程有哪些?

在常规情况下,我们直接使用 `string.length` 来获取字符串的长度。但是,对于汉字来说,每个汉字实际上由两个字节组成。因此,直接使用 `length` 属性会错误地计算字符串的长度。以下是一个获取字符串正确长度的示例代码:

csharpprivate void button1_Click(object sender, EventArgs e){ string chineseString=这是一段汉字测试字符串; int actualLength=chineseString.Length * 2; // 汉字长度为两个字节 Console.WriteLine(字符串的实际长度为: + actualLength);}

正常情况下,我们是直接去string的length的,但是汉字是有两个字节的,所以直接用length是错的。如下图:

所以应该用以下代码来获取长度:

private void button1_Click(object sender, EventArgs e) { string s = textBox1.Text; int i = GetLength(s); MessageBox.Show(i.ToString()); } public static int GetLength(string str) { if (str.Length == 0) return 0; ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; byte[] s = ascii.GetBytes(str); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } } return tempLen; }

运行结果如下图:

也可以用这个获取长度:

int i = System.Text.Encoding.Default.GetBytes(s).Length;

通过系统提供函数我们就可以获取中文的真实长度,是不是很简单

超简单的C语言入门教程有哪些?