0
public partial class Form1 : Form
{
    string[] names = new string [20]                  

  {"John","Susy","Obedia","Saul","Abram","Lincoln","Abraham","Eli","Kain","Abel",                                    


   "Will","Smitty","Scott","Julie","Ramona","Melissa","Todd","Lilly","Naomi","Leland"};

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //Question #1 Pop Names in listbox
        for (int i = 0; i < names.Length; i++)
        {
            listBox1.Items.Add(names[i]);
        }
    }

这就是我填充我的方式listbox1,但现在listbox2我想显示每个名称的长度。我想知道如何在 C# 代码中找到它?

4

2 回答 2

1

您可以使用以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    //Question #1 Pop Names in listbox
    for (int i = 0; i < names.Length; i++)
    {
        listBox1.Items.Add(names[i]);
        listBox2.Items.Add(names[i].Length);
    }
}
于 2012-06-20T16:56:04.507 回答
0

这看起来像家庭作业,所以我不会给出完整的答案。

您想使用String.LengthC# 中的属性来获取每个名称的长度。

string str = "Michael";
int len = str.Length;

现在,您可以选择是从listBox1自身编译属性,还是获取原始数组并对其进行迭代。

于 2012-06-20T16:57:00.910 回答