Results 1 to 3 of 3

Thread: sorting comma delimited strings

  1. #1

    Thread Starter
    Fanatic Member venerable bede's Avatar
    Join Date
    Sep 2002
    Location
    The mystic land of Geordies
    Posts
    1,018

    sorting comma delimited strings

    Ok

    If I have 2 strings :

    strA = "1,2,3" and strB = "3,2,1"

    and I compare them they obviously wont equal eachother.

    However in my logig because they both contain the same 3 numbers I want to be able to say well yes man they do equal eachother.

    This would require that I sort both strings.
    I have seen a number of approaches but none seem too concise.

    Any Ideas ?


    Thanks in Advance

    Parksie

  2. #2

    Thread Starter
    Fanatic Member venerable bede's Avatar
    Join Date
    Sep 2002
    Location
    The mystic land of Geordies
    Posts
    1,018

    Re: sorting comma delimited strings

    I just came across this which seems pretty tidy :
    Code:
    string input = "1,9,3,4,3,9,1,5,6,78,";
    string[] stringArray = input.Split( new char[] { ',' },
        StringSplitOptions.RemoveEmptyEntries );
    int length = stringArray.Length;
    int[] intArray = new int[length];
    for (int i = 0; i < length; i++)
    {
        try
        {
            intArray[i] = Convert.ToInt32( stringArray[i] );
        }
        catch (Exception)
        {
            // ignore
        }
    }
    Array.Sort( intArray );

    Parksie

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,109

    Re: sorting comma delimited strings

    Tidy, but does it do what you expect? I'd be tempted to take both arrays, Split(","), then iterate through one in a fashion like this:
    vb Code:
    1. A = String1.Split(",") 'Array 1
    2. B = String2.Split(",") 'Array 2
    3.  
    4. 'A quick check.
    5. if A.Length<>B.Length then
    6.  'They aren't the same.
    7. End if
    8.  
    9. 'A slower check
    10. 'Since they are both string arrays, this should work:
    11. Array.Sort(A)
    12. Array.Sort(B)
    13.  
    14. For x=0 to A.Length-1
    15.  If A(x) <> B(x) Then
    16.    'THey aren't the same
    17.    Exit For
    18.  End If
    19. Next
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width