Visual Basic 中的数组创建和填充问题 [英] Array creation and population issues in visual basic

查看:23
本文介绍了Visual Basic 中的数组创建和填充问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个关于我在 vb 中遇到的问题的快速问题.

just a quick question about an issue I am having in vb.

我需要创建一个数组,然后遍历一个字符串,将字符串值添加到数组中,只是它不存在,以生成一个唯一值的数组.

I need to create an array, then iterate through a string, adding the string value to the array only is it does not already exist, to produce an array of unique values.

我遇到的问题是 array.length 操作 - 在一个没有任何东西的数组上,我无法检索数组长度 (0),因此我无法将数组重新维度化为数组长度(必须是数组长度,因为数组从 0 开始索引),使我能够将新值添加到数组中,然后继续循环,直到检查所有值以查看它们是否存在于数组中(使用 contains)并且该值只包含独特的价值..

The issue I am having is with the array.length operation - on a array that is nothing I am unable to retrieve the array length (0), as such I am unable to redimensionalise the array to be array length (must be array length as arrays are indexed from 0), providing me the ability to add the new value to the array and then continue the loop until all values have been checked to see if they exist within the array (using contains) and the value contain only unique values..

一直在咬我的头几个小时:)

Been nipping my head for hours :)

谢谢马丁

推荐答案

我必须假设您正在使用 VB.Net,所以我会相应地回答.您真正要寻找的答案是:

I must assume that you are working with VB.Net, so I will answer accordingly. The answer you are literally looking for is:

Public Function GetUniqueChars(text As String) As Char()
        Dim uniqueChars() As Char

        ReDim uniqueChars(0)
        If String.IsNullOrEmpty(text) Then Return uniqueChars

        uniqueChars(0) = text(0)

        For Each c In text.Substring(1)
            If Not uniqueChars.Contains(c) Then
                ReDim Preserve uniqueChars(uniqueChars.Length)
                uniqueChars(uniqueChars.Length - 1) = c
            End If
        Next

        Return uniqueChars

    End Function

但是,从 Net 3.5 开始,您可以使用 LINQ 将此功能减少到一行:

However, starting with Net 3.5 you can use LINQ to reduce this function to one line:

uniqueChars = text.Distinct().ToArray

这篇关于Visual Basic 中的数组创建和填充问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆