Results 1 to 28 of 28

Thread: split strings into integers

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    split strings into integers

    I'm trying to split an inputted string (txtStart.text) into separate integers. The split function works fine for me, but I can't figure out how to store the each part of the array... any ideas? Thanks

    This is my current code that I based on an example from MSDN library:

    Code:
        Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
            SplitStringIntoWords()
        End Sub
    
        Private Function SplitStringIntoWords() As Integer
            Dim strComplete As String = txtStart.Text
    
            Dim strWords() As String
            Dim strSeparators() As Char = {"/"c, "-"c}
    
    
            strWords = strComplete.Split(strSeparators)
            Dim i As Integer
            For i = 0 To UBound(strWords)
                MessageBox.Show(strWords(i))
            Next
    
    
        End Function

  2. #2
    Member
    Join Date
    Feb 2009
    Posts
    55

    Re: split strings into integers

    instead of ubound u can use Len(string) but besides that,

    im not sure exactly what you did there... but what u need to do is very simple string "manipulation"
    use the function InStr() to locate where is the seperation then use the function Mid twice, once for the first part (before the seperator) and second for the second part (after the seperator....
    then u will have two strings , first part and second part
    then, the last step should be converting to Integer with the function Val () (i think)

  3. #3
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: split strings into integers

    strWords is already an array. What else are you looking for?
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: split strings into integers

    Try to replace the For loop?
    vb Code:
    1. Dim i As Integer = 0
    2. Dim l As New List(Of String)
    3. While i < strWords.Length
    4.         Dim ans As Integer = CInt(Val(strWords(i)))
    5.         'Do whatever you want with ans. Here, I put it into a list.
    6.         l.Add(ans)
    7.         i += 1
    8. End While
    By the way, this won't work unless you use VS 2005 or higher (the others don't have List). If you aren't using one of these, use this:
    Code:
    Dim l As Integer(strWords.Length - 1)
    and replace l.Add(ans) with l(i) = ans.

  5. #5
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: split strings into integers

    Code:
        Private Function SplitStringIntoWords() As List(Of Integer)
            'If this is to manipulate dates there are other ways
            Dim strWords() As String
            Dim asIntegers As New List(Of Integer)
            Dim strSeparators() As Char = {"/"c, "-"c, " "c} '/-space
    
            strWords = txtStart.Text.Split(strSeparators, StringSplitOptions.RemoveEmptyEntries)
            Dim i As Integer
            For x = 0 To strWords.Length - 1
                If Integer.TryParse(strWords(x), i) Then
                    asIntegers.Add(i)
                End If
            Next
            Return asIntegers
        End Function
    
        'Test
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim retval As New List(Of Integer)
            retval = SplitStringIntoWords()
            For x As Integer = 0 To retval.Count - 1
                Debug.WriteLine(retval(x).ToString)
            Next
        End Sub
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  6. #6

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    Thank you very much. I'm quite sure I understand everything now.

    One more question...If I inputted a date MMDDYYYY in txtStart.text, how would I store each MM, DD, and YYYY into separate integers. For example,

    input: 04072009
    and I want it to store:
    startMonth = 04
    startDay = 07
    startYear = 2009

    Sorry if this is so basic... I'm in an intro course. Thanks again

  7. #7
    Frenzied Member Campion's Avatar
    Join Date
    Jul 2007
    Location
    UT
    Posts
    1,098

    Re: split strings into integers

    The best way, is to turn the string into a date, and then use DATE.getDate, getMonth, and getYear to parse out what you need.

  8. #8

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    Ok... thanks. Can you give me an example of what this means / how to do it?

  9. #9
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: split strings into integers

    Code:
            Dim d As Date
            txtStart.Text = "04072009" 'test
            If Date.TryParseExact(txtStart.Text, _
                                  "MMddyyyy", _
                                  Nothing, _
                                  Globalization.DateTimeStyles.None, d) Then
                'date is good format
                Dim startMonth As Integer = d.Month
                Dim startDay As Integer = d.Day
                Dim startYear As Integer = d.Year
            Else
                'date is bad
            End If
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  10. #10
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Re: split strings into integers

    Whoa, whoa... There is a much easier for going through an array this way!

    Use: For Each

    Code:
    Dim splitChars() As Char = {"/"c, "-"c}
    Dim allTheNumbers() As String = txtStart.Text.Split(splitChars)
    For Each iNumber As String In allTheNumbers
        MessageBox.Show(iNumber)
    Next
    It will loop the code for every number in "allTheNumbers" and "iNumber" will be that number.
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

  11. #11
    Frenzied Member Campion's Avatar
    Join Date
    Jul 2007
    Location
    UT
    Posts
    1,098

    Re: split strings into integers

    Not to say that you using a textbox is a bad method, but wouldn't it make more sense to use either a date/time picker control or calendar control?

  12. #12
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: split strings into integers

    Quote Originally Posted by arsmakman View Post
    Whoa, whoa... There is a much easier for going through an array this way!

    Use: For Each

    Code:
    Dim splitChars() As Char = {"/"c, "-"c}
    Dim allTheNumbers() As String = txtStart.Text.Split(splitChars)
    For Each iNumber As String In allTheNumbers
        MessageBox.Show(iNumber)
    Next
    It will loop the code for every number in "allTheNumbers" and "iNumber" will be that number.
    This would also work if the input was
    aa-bb-zzzz
    which, last I knew, weren't numbers, except maybe in base 26.

    @crab - When asking a question be specific. You were asking about manipulating dates, yet in your original post you didn't mention the word date.

    I would agree that using a DTP would be my first choice, less chance for the user to make a mistake.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  13. #13

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    Maybe...my assignment is to input two dates in a textbox and output all the dates in between the two dates.

    Our plan is to convert the date string into separate integers (MM , DD, and YYYY as stated) and use several counters and loops to add/output one day at a time until the last day.

    Is there clearly a better a way of doing this?

    Heres the flowchart

  14. #14

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    @dbasnett

    i'll try to be more specific in the future... thanks

  15. #15
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: split strings into integers

    honestly, if you wanted to take 2 dates, and get all date values in between those 2 dates, it is as simple as this:

    Code:
            Dim StartDate As Date = #1/1/2009#
            Dim EndDate As Date = #4/7/2009#
    
            Do Until StartDate = EndDate.AddDays(-1)
                StartDate = StartDate.AddDays(1)
                Debug.WriteLine(StartDate)
            Loop
    however if your teacher gave you that flowchart to use to map out your code logic, then obviously they want you to just to do this as a learning exercise in logic, and you will probably have to do it the ridiculously non real world hard way

  16. #16
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: split strings into integers

    using post #9 to validate both start and end dates

    Code:
            Dim stDt As DateTime
            Dim endDt As DateTime
            Dim dtDiff As TimeSpan
            'sample data
            stDt = DateTime.Now
            endDt = stDt.AddDays(100)
            endDt = endDt.AddHours(13)
    
            dtDiff = endDt.Subtract(stDt)
    I agree with Matt, about un-real.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  17. #17
    Member
    Join Date
    Feb 2009
    Posts
    55

    Re: split strings into integers

    guys,
    he is new at programing and your "throwing" all this code.... im sure he wants it simple
    ofcourse that "simple" depends on preseption
    in any case, here is simple (yet primitive) way for you...

    mainstring :04072009

    the input is a string , which means you can access each char (cell) individually
    so...if you want to get the "4" then you can write mainstring(2) , cell number 2.

    as for your example :
    startMonth = mainstring(1) & mainstring(2)
    startDay = mainstring(3) & mainstring(4)
    startYear = mainstring(5) & mainstring(6) & mainstring(7) & mainstring(8)

    by the way, & is appending (adding) to the end of the string

  18. #18
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: split strings into integers

    And the dashes? Just thought I'd point that out, so that code exactly is not used. But anyways, that is not a good way. What if you have 30 dates in the textbox or something? And if they're in a different format? Any change would require completely new (and long) code.

  19. #19
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: split strings into integers

    Quote Originally Posted by sharik View Post
    guys,
    he is new at programing and your "throwing" all this code.... im sure he wants it simple
    ofcourse that "simple" depends on preseption
    in any case, here is simple (yet primitive) way for you...

    mainstring :04072009

    the input is a string , which means you can access each char (cell) individually
    so...if you want to get the "4" then you can write mainstring(2) , cell number 2.

    as for your example :
    startMonth = mainstring(1) & mainstring(2)
    startDay = mainstring(3) & mainstring(4)
    startYear = mainstring(5) & mainstring(6) & mainstring(7) & mainstring(8)

    by the way, & is appending (adding) to the end of the string
    for someone criticizing what other people are posting, did you even try this code you are tying here? I can only imagine that you did not, since arrays start at index 0, meaning your startMonth variable will have a value of "40" not "04" based on the code you are showing there. There is no char at index 8 in a 8 character string, its 0-7, so the code would crash on the startYear assignment line.

  20. #20
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: split strings into integers

    Quote Originally Posted by crabramson View Post
    Thank you very much. I'm quite sure I understand everything now.

    One more question...If I inputted a date MMDDYYYY in txtStart.text, how would I store each MM, DD, and YYYY into separate integers. For example,

    input: 04072009
    and I want it to store:
    startMonth = 04
    startDay = 07
    startYear = 2009

    Sorry if this is so basic... I'm in an intro course. Thanks again
    You have to convert the input into a String object (if it's not already a string), and then use Date.TryParseExact or Date.ParseExact to parse that string into a Date object. Once you have the Date object, you can access its Year, Month and Day properties to get what you need.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  21. #21

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    @kleinma

    about the line: Debug.WriteLine(StartDate)
    if I'm outputting to a text file then would it work if debug is the name of my streamwriter?

  22. #22
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: split strings into integers

    If you are asking, can you replace the word "debug" with the name of your streamwriter variable, then yes you can, since streamwriter also has a WriteLine() method.

  23. #23
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Re: split strings into integers

    Debug.Print, writes to the debug window.
    You could copy-paste the text from there into a file or you could do this, to save directly to a file:

    Code:
            Dim StartDate As Date = #1/1/2009#
            Dim EndDate As Date = #4/7/2009#
            Dim ListOfDates As String = ""
    
            Do Until StartDate = EndDate.AddDays(-1)
                StartDate = StartDate.AddDays(1)
                 ListOfDates &= StartDate & vbNewLine
            Loop
    
            IO.File.WriteAllText ("C:\Output.txt", ListOfDates)
    This will save the dates as a list to the file C:\output.txt
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

  24. #24
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: split strings into integers

    Just to add for crabramson, I'm not sure if you'll want the actual time part of the Date returned by:

    Code:
    Debug.WriteLine(StartDate)
    So you can do:

    Code:
    Debug.WriteLine(StartDate.ToString("MM-dd-yyyy"))

  25. #25
    Member
    Join Date
    Feb 2009
    Posts
    55

    Re: split strings into integers

    Originally Posted by sharik View Post
    guys,
    he is new at programing and your "throwing" all this code.... im sure he wants it simple
    ofcourse that "simple" depends on preseption
    in any case, here is simple (yet primitive) way for you...

    mainstring :04072009

    the input is a string , which means you can access each char (cell) individually
    so...if you want to get the "4" then you can write mainstring(2) , cell number 2.

    as for your example :
    startMonth = mainstring(1) & mainstring(2)
    startDay = mainstring(3) & mainstring(4)
    startYear = mainstring(5) & mainstring(6) & mainstring(7) & mainstring(8)

    by the way, & is appending (adding) to the end of the string
    Quote Originally Posted by kleinma View Post
    for someone criticizing what other people are posting, did you even try this code you are tying here? I can only imagine that you did not, since arrays start at index 0, meaning your startMonth variable will have a value of "40" not "04" based on the code you are showing there. There is no char at index 8 in a 8 character string, its 0-7, so the code would crash on the startYear assignment line.
    i wasn't criticizing , although i understand why it might be read like that,

    i'm a beginner (obviously) and i will not allow my self to criticize , and besides even if i wasn't beginner , i wouldn't do that...

    i always appreciated anything i could find here, and respect all the people here, using their time to help and post answers and codes and tips, thats alot of devotion right there...
    so i definitely have high respect for this form and people in it....

    apologies to everyone, your the greatest

    as for the code,
    no i didn't try the code, i dont have VS install on this machine, it was just the idea, he would be able to make the correct changes.don't get me wrong, you are very correct that i made the mistake, no doubt in that.
    Last edited by sharik; Apr 7th, 2009 at 03:32 PM. Reason: reference

  26. #26

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    Quote Originally Posted by ForumAccount View Post
    Just to add for crabramson, I'm not sure if you'll want the actual time part of the Date returned by:

    Code:
    Debug.WriteLine(StartDate)
    So you can do:

    Code:
    Debug.WriteLine(StartDate.ToString("MM-dd-yyyy"))

    That causes ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime. Parameter name: value

  27. #27

    Thread Starter
    Junior Member
    Join Date
    Mar 2009
    Posts
    21

    Re: split strings into integers

    works perfectly, thanks
    Last edited by crabramson; Apr 15th, 2009 at 11:09 PM.

  28. #28
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    Re: split strings into integers

    Quote Originally Posted by crabramson View Post
    That causes ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime. Parameter name: value
    Errr... if StartDate is valid then no it doesn't.

    Code:
    Dim StartDate As Date = #4/7/2009 12:00:00 PM# 
    Debug.WriteLine(StartDate.ToString("MM-dd-yyyy"))

Tags for this Thread

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