Results 1 to 13 of 13

Thread: Using the .SubString Function to Reverse the string

  1. #1

    Thread Starter
    Member
    Join Date
    Feb 2013
    Location
    Cincinnati, Ohio
    Posts
    35

    Smile Using the .SubString Function to Reverse the string

    I have an assignment where we have to a number of things such as count the vowels, words, and reverse strings. I was able to write the code for the vowels and the words but am lost on the reverse. Here is the section of the assignment the professor asked.

    6) Write the code for the “Reverse” button click event. The subroutine should get the text from txtSentence and pass it to a function called ReverseString. The ReverseString function should reverse the string and return it. For example ReverseString( “ABC” ) should return “CBA”. The “Reverse” button click subroutine should then update the text in txtSentence with the reversed string. You cannot use the StrReverse function. Use .Substring to extract each letter but assemble the characters back together using concatentation so that the first character ends up as the last.

    I understand the concept of what it is doing and but don't know how to start it. I have used the .substring in the past to output part of the string. Can anyone give me some advice on how to go about it or even a little example? Here is the code I have written for the vowels, words, as well as the overall defined variables so far.
    Thanks again.

    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim str As String
            Dim total As Integer
    
            total = 0
            str = txtSentence.Text
            'look for each vowel and add the count to total
            total = total + CharCount(str, "A")
            total = total + CharCount(str, "E")
            total = total + CharCount(str, "I")
            total = total + CharCount(str, "O")
            total = total + CharCount(str, "U")
            total = total + CharCount(str, "Y")
    
            'display results
            MsgBox("Total Vowels = " & total)
    
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim str As String
            Dim i, l, words As Integer
            str = txtSentence.Text
            str = LTrim(str) 'removes leading blank spaces
            str = RTrim(str) ' removes trailing blank spaces
            l = str.Length
            i = 0
            words = 0
            While (i < l)
                If str(i) = " " Then
                    words = words + 1
                    i = i + 1
                    While str(i) = " " ' removes continuous blank spaces
                        i = i + 1
                    End While
                Else
                    i = i + 1
                End If
    
            End While
            words = words + 1 ' adds the last word
            MessageBox.Show("WORDS =" & words)
        End Sub
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            Dim random As String = "asfdgasfdgasfdgasfd11"
            Dim length As Integer = Nothing
            length = Random.Length
            Console.WriteLine(random.Length)
            Console.WriteLine(length)
            Console.WriteLine()
            Console.WriteLine()
            Console.ReadLine()
    
            Dim curStart = 0
            Dim loopCounter = 0
            While (curStart < random.Length)
                Console.WriteLine(random.Substring(curStart, System.Math.Min(20, length - 20 * loopCounter)))
                curStart = curStart + 20
                loopCounter = loopCounter + 1
            End While
        End Sub
    
        Private Function CharCount(ByVal str As String, ByVal findCH As Char) As Integer
    
            Dim idx, Ln, cnt As Integer
            Dim ch As String
    
            Ln = str.Length
            cnt = 0
    
            findCH = Char.ToUpper(findCH) 'make sure char is an uppercase
    
            For idx = 0 To Ln - 1
                'read individual letters from string and convert to uppercase
                ch = CChar(str.Substring(idx, 1).ToUpper) 'convert to char
                If ch = findCH Then
                    cnt = cnt + 1 'found a match increment the count
                End If
            Next
            Return cnt
    
        End Function
    
    
        Private Sub txtSentence_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSentence.TextChanged
    
        End Sub
    End Class

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

    Re: Using the .SubString Function to Reverse the string

    Hint:

    Code:
        Private Function ReverseIt(someString As String) As String
            Dim rv As String
            For x As Integer = someString.Length - 1 To 0 Step -1
                rv &= 'complete this statement
            Next
            Return rv
        End Function
    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

  3. #3

    Thread Starter
    Member
    Join Date
    Feb 2013
    Location
    Cincinnati, Ohio
    Posts
    35

    Re: Using the .SubString Function to Reverse the string

    Quote Originally Posted by dbasnett View Post
    Hint:

    Code:
        Private Function ReverseIt(someString As String) As String
            Dim rv As String
            For x As Integer = someString.Length - 1 To 0 Step -1
                rv &= 'complete this statement
            Next
            Return rv
        End Function
    Sorry I am still confused. This is my first semester of this. So do I then type the txtbox I am getting the string from then .substring followed by the numbers in the parenthesis?

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

    Re: Using the .SubString Function to Reverse the string

    Sorry, I wrote a Function to do the work of reversing. See if this helps.

    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            txtSentence.Text = ReverseIt(txtSentence.Text)
        End Sub
    
        Private Function ReverseIt(someString As String) As String
            Dim rv As String
            For x As Integer = someString.Length - 1 To 0 Step -1
                rv &= 'complete this statement
            Next
            Return rv
        End Function
    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

  5. #5

    Thread Starter
    Member
    Join Date
    Feb 2013
    Location
    Cincinnati, Ohio
    Posts
    35

    Re: Using the .SubString Function to Reverse the string

    Quote Originally Posted by dbasnett View Post
    Sorry, I wrote a Function to do the work of reversing. See if this helps.

    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            txtSentence.Text = ReverseIt(txtSentence.Text)
        End Sub
    
        Private Function ReverseIt(someString As String) As String
            Dim rv As String
            For x As Integer = someString.Length - 1 To 0 Step -1
                rv &= 'complete this statement
            Next
            Return rv
        End Function

    Ok So I have been trying and can't get it. I tried
    Code:
    rv &= txtsentence.Substring(0, 0)
    But obviously that is wrong. I tried changing the numbers in the parenthesis but that didn't do anything. Can someone walk me through the statement so I can understand it or have an easy way of explaining it. Sorry again for my asking I just can't figure it out.

  6. #6
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Using the .SubString Function to Reverse the string

    SomeString = "0123456789"
    rv = ""
    x = 9
    rv = SomeString.SubString(9, 1) = "9"
    x = 8
    rv = rv & SomeString.SubString(8,1) = "98"

    etc.

    Now just do it without using literal numbers!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

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

    Re: Using the .SubString Function to Reverse the string

    Walk you through what? Do you know what substring does, and what the arguments are for? If you do, then consider the steps that you are trying to perform:

    For every character in the string, starting with the rightmost character, add it to a new string. Therefore, the steps would be these:

    1) Get the last character in the string.
    2) Concatenate it onto the new string.

    You are doing #2 fine, so the problem would have to be with step #1, which is entirely based on the arguments in the line you just posted. If you don't know what those arguments are, we could explain them, but we'd be doing no more than paraphrasing what is written in MSDN on the subject of Substring. Sometimes that would help, since MSDN isn't always written in a way that is clear to everybody, but I think that the writing is fairly clear for the Substring method.

    However, if after reading what MSDN has to say about Substring, you are still unclear on the arguments, then I think that you would benefit the greatest by putting a breakpoint on the line where you use Substring, and when execution stops on the breakpoint, highlight the Substring(0,0) part and press Shift+F9 to see what it returns. When you do that, you can try changing the arguments and reevaluating, so you can see for yourself what Substring does, which should be far more informative than anything we can say. Besides, if you haven't used breakpoints, there is no more useful tool you can have, and they are super easy, so just learning that would be worth the minor time involved.
    My usual boring signature: Nothing

  8. #8
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: Using the .SubString Function to Reverse the string

    Quote Originally Posted by Roxide View Post
    I tried changing the numbers in the parenthesis but that didn't do anything.
    Here's the documentation for String.Substring(Int32, Int32). Have a look at it and then try to see what dbasnett has set up for you in the loop.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

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

    Re: Using the .SubString Function to Reverse the string

    Try something like this:
    Code:
            Dim original As String = "0123456789"
            Dim reversed As String = original
            Dim length As Integer = original.Length
            If length > 1 Then
                reversed = String.Empty
                For i As Integer = length To 1 Step -1
                    reversed &= original.Substring(i - 1, 1)
                Next
            End If
            MessageBox.Show(reversed)
    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 -

  10. #10

    Thread Starter
    Member
    Join Date
    Feb 2013
    Location
    Cincinnati, Ohio
    Posts
    35

    Re: Using the .SubString Function to Reverse the string

    Quote Originally Posted by dbasnett View Post
    Sorry, I wrote a Function to do the work of reversing. See if this helps.

    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            txtSentence.Text = ReverseIt(txtSentence.Text)
        End Sub
    
        Private Function ReverseIt(someString As String) As String
            Dim rv As String
            For x As Integer = someString.Length - 1 To 0 Step -1
                rv &= 'complete this statement
            Next
            Return rv
        End Function
    AHA I think I finally figured it out. Would this be correct?

    Code:
       rv &= txtSentence.Text.Substring(x, 1)

  11. #11
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Using the .SubString Function to Reverse the string

    Not sure whether you'll get extra credit for doing it correctly, but you should probably know that iterating through every Char in the String backwards (or every one-character long substring, which is essentially the same thing) does not reverse a string reliably in .NET. It fails to account for multi-character glyphs (for example where a letter has an accent, this can be formed by the base character followed by a combining character - when you reverse these characters, the combining character ends up following the character that was after the accented character in the original string, so the accent changes which letter it is on when the string is reversed) and characters that exist outside the Basic Multilingual Plane that are represented as two Chars that form a Surrogate Pair - reverse these two characters and you've corrupted the string.

    The last time I came across this assignment (note, there have been no reports of needing to do this for a real program) I did find a class that split up a string into singly glyphs, keeping all combining characters together with their base character, and not splitting up surrogate pairs, then all you had to do was iterate over it and stitch the strings together in reverse, however, I can't remember what it was called, don't know if I actually posted it because the search on here is a bit wonky, and don't have the test code I wrote on this computer.

  12. #12
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Using the .SubString Function to Reverse the string

    Ah, it's StringInfo.GetTextElementEnumerator()
    Pass it a string and get back an iterator of strings. There doesn't seem to be an Enumerable version you can pipe directly to Linq's Reverse method, so you'd need to wrap it as this SO answer (C#) does: http://stackoverflow.com/a/15111719

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

    Re: Using the .SubString Function to Reverse the string

    Quote Originally Posted by Roxide View Post
    AHA I think I finally figured it out. Would this be correct?

    Code:
       rv &= txtSentence.Text.Substring(x, 1)
    No. It should be one of these

    Code:
                rv &= someString(x) 'complete this statement
                'or
                rv &= someString.Substring(x, 1) 'complete this statement
    EG's solution
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            txtSentence.Text = ReverseIt(txtSentence.Text) 'has çbā̈ in text field as test
        End Sub
    
        Private Function ReverseIt(someString As String) As String
            Dim its As Globalization.TextElementEnumerator = Globalization.StringInfo.GetTextElementEnumerator(someString)
            Dim sb As New System.Text.StringBuilder
            Do While its.MoveNext
                sb.Insert(0, its.GetTextElement)
            Loop
            Dim rv As String = sb.ToString
            Return rv
        End Function
    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

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