c# - 从零开始索引
问题描述
我在这个程序中遇到了问题,它是为将 Unicode 字符转换为 32 位格式而编写的;在从零开始的索引部分。索引是否需要从零开始?
为什么不能从数字 1 开始?请好好解释这部分。
int a;
textBox2.Text = " ";
for (int i = 0; i < textBox1.Text.Length; i++)
{
a = Char.ConvertToUtf32(textBox1.Text.Substring(i, 1), 0);
textBox2.Text = a.ToString();
if (textBox1.Text == " ")
{
textBox2.Text = " " ;
}
}
解决方案
字符串类似于数组,c# 中任何数组类型的索引都是从 0 开始的。至于代码的效率,您还可以将 if check 移到循环内部,移到外部,因为它独立于任何索引。请参阅下面的示例代码:
/// <param name="source"> equivalent to TextBox1.Text in original post</param>
public static int[] ConvertToUtf32(string source)
{
int[] result = new int[source.Length]; //equivalent to all the chars displayed in TextBox2.Text in original post
if (source.Equals(" "))
{
result[0] = ' ';
}
else
{
for (int i = 0; i < source.Length; i++)
{
result[i] = Char.ConvertToUtf32(source.Substring(i, 1), 0);
}
}
return result;
}
推荐阅读
- c# - 无法将数据加载到 ComboBox C#
- python - Dask dataframe concat 将列类型从“int”更改为“float”
- asp.net - 什么是 .NetCore 分析器
- javascript - Mongoose 具有相同的保存和更新中间件功能
- flutter - 如何从 Flutter Firestore 中的嵌套集合中获取数据?
- xamarin - 在请求位置许可时,应用程序仅在 iOS 中崩溃。在 xamarin
- node.js - 使用nodejs驱动程序在mongodb中的dd.mm.yyyy中的日期格式
- c# - 处理所有子控件和数据 - C#
- c# - 更新父实体而不更改子实体
- spring-mvc - 异常:com.fasterxml.jackson.core.JsonParseException:无法识别的令牌“代码”:期待(“真”、“假”或“空”)