首页 > 解决方案 > 从零开始索引

问题描述

我在这个程序中遇到了问题,它是为将 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#

解决方案


字符串类似于数组,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;
}

推荐阅读