Link to home
Start Free TrialLog in
Avatar of vb7guy
vb7guyFlag for United States of America

asked on

String Lenght Compare

I have an old vb.net application that reads some data from ini file and sets them to few different variables.  Now, I want to be able to compare the lengh of these values and figure out which one which variable has the longest string lenght.
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Just use the Len function and some kind of loop to get the max. Something like:
max = str1
If Len(str2) > Len(max) Then
max = str2
End If

Open in new window


If it's only two values, then just compare Len(str1) > Len(str2)
Or, for a more .Netish approach, use the .Length() property:

    If strA.Length > strB.Length Then

    End If

See String.Length: http://msdn.microsoft.com/en-us/library/system.string.length.aspx

For the second part, if you need to compare a bunch of these variables, do the variable names have any kind of pattern to them?
Avatar of vb7guy

ASKER

I know how to compare two variables and figure out which one is longer.  I have about 5 variables.  For example.
sStrVal1
sStrVal2
sStrval3
sStrval4
sStrval5
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's an approach if your variables follow a pattern as you've shown.  Note that the variables are declared as PUBLIC:
Public Class Form1

    Public sStrVal1 As String = "abcd"
    Public sStrVal2 As String = "abcde"
    Public sStrVal3 As String = "ab"
    Public sStrVal4 As String = "abcdef"
    Public sStrVal5 As String = "a"

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim longestName As String = ""
        Dim longestValue As String = ""

        Dim varName As String
        Dim varValue As String
        For i As Integer = 1 To 5
            varName = "sStrVal" & i
            varValue = CallByName(Me, varName, CallType.Get)
            If longestName = "" OrElse varValue.Length > longestValue.Length Then
                longestName = varName
                longestValue = varValue
            End If
        Next

        MessageBox.Show(longestName & " = " & longestValue)
    End Sub

End Class

Open in new window


*This uses the legacy VB6 CallByName() function which requires those variables to be Public.  The same thing can be done with the newer .Net REFLECTION techniques, allowing access to variables that are Private, but the code isn't as succinct.  Let me know if you want to see an example of that.
Avatar of vb7guy

ASKER

Thanks to TommySzalapski, this is what I was looking for.