none
Convert string in array to integer?

    Question

  • I am using vb express. I need to convert a string that I have stored in an array into an integer so I can add them together. Feel free to ask questions. Thanks
    Wednesday, March 21, 2007 1:44 AM

Answers

  • Two ways of converting a string to an int32 integer would be Int32.Parse(...) and Int32.TryParse(...).  The main difference is that Parse throws an exception if it can't parse the string whereas TryParse returns false.  If you expect the conversion to work in almost all cases Parse() is appropriate, just add a try-catch block  to handle (infrequent) problems.  If you are less confident in the validity of the string contents use TryParse() and check the return value to see if it worked.

    Another alternative would be the various Convert.ToInt32() overloads.

    But all the foregoing assumes you have an actual string type variable not an array.

    Note also that parsing a string can be a culturally sensitive operation.  For example several European conventions use a comma (,) as the separator in a decimal number not a period (.).  That's probably not relevant if you are converting to an integer but in more general cases it is something you may have to thing about.

     

    Wednesday, March 21, 2007 6:07 AM
    Moderator

All replies

  • To convert string to Integer, Use CInt(StringToConvert). In your case, it should be like this

    Dim i as integer

    Dim total as Integer=0

    for i=o to array.Count

    total=total+Cint(array(i))

    Next

    Did not test the code, so it should be at least close to that. You may also want to check if the input is numeric. Use Char.IsDigit() for the purpose.

     

     

    Wednesday, March 21, 2007 2:32 AM
  • Two ways of converting a string to an int32 integer would be Int32.Parse(...) and Int32.TryParse(...).  The main difference is that Parse throws an exception if it can't parse the string whereas TryParse returns false.  If you expect the conversion to work in almost all cases Parse() is appropriate, just add a try-catch block  to handle (infrequent) problems.  If you are less confident in the validity of the string contents use TryParse() and check the return value to see if it worked.

    Another alternative would be the various Convert.ToInt32() overloads.

    But all the foregoing assumes you have an actual string type variable not an array.

    Note also that parsing a string can be a culturally sensitive operation.  For example several European conventions use a comma (,) as the separator in a decimal number not a period (.).  That's probably not relevant if you are converting to an integer but in more general cases it is something you may have to thing about.

     

    Wednesday, March 21, 2007 6:07 AM
    Moderator