Results 1 to 13 of 13

Thread: [RESOLVED] Swap words in a string

  1. #1

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Resolved [RESOLVED] Swap words in a string

    i want to write a code to swap the words in a string.
    Input - I like cake
    Output - cake I like

    To do this it would be great if there is a way to determine the index of each word.Like
    1- I
    2- like
    3- cake
    Then I can swap the words.But I have no idea how to do it.
    Currently I have written the code to count the number of words in a string and to get the average.

    Code:
     Dim str As String = Me.t1.Text
    
            Dim strA() As String = str.Split(" ")
    
            Dim TChrs As Int32
    
            Dim i As Int32
    
            For i = strA.Length - 1 To 0 Step -1
    
                TChrs += strA(i).Length
    
            Next
    
            MsgBox("Number of words = " & strA.Length)
    
            MsgBox("Average Length = " & TChrs / strA.Length)
    Can any one please help me with this

  2. #2
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Swap words in a string

    Do you always want the last word in the string to be the first word in the string after the swap?

  3. #3

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Quote Originally Posted by Hack View Post
    Do you always want the last word in the string to be the first word in the string after the swap?
    Thank you sir for replying!
    No I dont always want that to happen. Actually I am trying to build a search method for database records.So I want to search names.If someone search for "Chandler Muriel Bing" ,then the application should search for "Chandler Muriel Bing" , "Chandler Bing Muriel" , "Muriel Bing Chandler" , "Muriel Chandler Bing" , "Bing Chandler Muriel" and "Bing Muriel Chandler".
    Thats the idea.
    It will be so helpful if you could help me in anyway.

    Thank you

  4. #4
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Swap words in a string

    Why not just use the SQL LIKE keyword. If you do
    Code:
    SELECT whatever, whatever, whatever
    FROM table
    WHERE username 
    LIKE '%Chandler%'
    This would pull all names that had Chandler in it regardless of where it was or how many names there were in that field.

  5. #5

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Quote Originally Posted by Hack View Post
    Why not just use the SQL LIKE keyword. If you do
    Code:
    SELECT whatever, whatever, whatever
    FROM table
    WHERE username 
    LIKE '%Chandler%'
    This would pull all names that had Chandler in it regardless of where it was or how many names there were in that field.
    I have already tried that.This is a sample of my current code

    Code:
    Private Sub txtProperty_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt.TextChanged
            Dim s As String = Me.txt.Text
            For i As Integer = s.Length - 1 To 1 Step -1
                s = s.Insert(i, "%")
            Next
    
            Dim w_to_v As String = Replace(s, "w", "[wv]")
            Dim v_to_w As String = Replace(s, "v", "[wv]")
    
            Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=E:\Band6_2011-10-01.mdb;Jet OLEDB:Database Password=3rdband"
            Dim con As OleDbConnection = New OleDbConnection(constr)
    
            If Me.txt2.Text = "" And Me.txt.Text <> "" Then
                Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT Indv_NAME As [Name in NIC] from tbl_Indv INNER JOIN tbl_householdinfo ON tbl_Indv.UNIQUE_ID = tbl_householdinfo.UNIQUE_ID where (Indv_NAME Like '%" & w_to_v & "%' or Indv_NAME Like '%" & v_to_w & "%' )", con)
    
     Dim ds As New DataSet()
                'fill the datset
                da.Fill(ds)
                'attach dataset to the datagrid
                DataGridView1.DataSource = ds.Tables(0)
                ds = Nothing
                da = Nothing
                con.Close()
                con.Dispose(
             End sub
    This will give a pretty good result.But with this code there is a problem.
    Lets say there is an entry named "Bing Chandler".If we search for "Chandler Bing" for some reason the data grid is emptied.
    If I search for Chandler or Bing separately then i will get the record.
    Do you know what the reason might be?
    Is it because i have it in a textchanged method?
    Last edited by chathu1234; Nov 29th, 2011 at 09:01 AM. Reason: missed a piece of coding

  6. #6
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Swap words in a string

    Quote Originally Posted by chathu1234 View Post
    Lets say there is an entry named "Bing Chandler".If we search for "Chandler Bing" for some reason the data grid is emptied.
    If I search for Chandler or Bing separately then i will get the record.
    That makes perfect sense. That is how the LIKE keyword works.
    Quote Originally Posted by chathu1234 View Post
    Do you know what the reason might be?
    See above

    Why the need for the JOIN? What happens if you just do
    Code:
    "SELECT Indv_NAME As [Name in NIC] 
    from tbl_Indv 
    where Indv_NAME 
    Like '%" & w_to_v & "%' 
    or 
    Indv_NAME Like '%" & v_to_w & "%' "

  7. #7

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Sorry about the JOIN.It was to get a value from the other table.
    Why the above code wont work for me is that I want to find people with a certain name.But I have a database with over 8,00,000 names and they are Sinhala(Sri Lankan) names and very easily misspelled.
    The above code helps me with the misspeling thing but I cant find the person named "Ranjit Fernando" if the user search for "Fernando Ranjit"
    But the user can search for "ranjt frnnd" or "ranjithhh ferrrrnandoaa" or whatever but cant search if the names are swapped.
    I learnt VB on my own so I dont know methodical explanation for this issue.

    I have written a code just now which will swap two words in a string.

    Code:
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim str As String = Me.t1.Text
    
            Dim strA() As String = str.Split(" ")
    
            Dim ne(100) As String
            ne(0) = strA(1)
            ne(1) = strA(0)
    
            MessageBox.Show(ne(0) + " " + ne(1))
    
        End Sub
    this works perfectly.But its for two words.Can you help me implement this code for any number of words?

    Thank you

  8. #8
    Frenzied Member
    Join Date
    Mar 2004
    Location
    Orlando, FL
    Posts
    1,618

    Re: Swap words in a string

    Use strA.Length - 1 to find the index of the last word instead of assuming 1.
    Sean

    Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.

  9. #9
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Swap words in a string

    Quick example. This is using a fixed string for testing purposes. You will need to change "I like oat meal cookies" to the name of the field containing all the names. First, store them in an array and just iterate through them adding an OR to your SELECT clause each iteration.
    vb.net Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Dim sString As String = "I love oat meal cookies"
    3.         Dim sLIKEClause As String = String.Empty
    4.         Dim arrString() As String = Split(sString, " ")
    5.         sLIKEClause = "LIKE Indv_NAME = '%" & arrString(0).ToString & "%' "
    6.         For i As Integer = 0 To arrString.Length - 1
    7.             sLIKEClause = sLIKEClause & " OR Indv_NAME LIKE '%" & arrString(i).ToString & "%' "
    8.         Next
    9.         MessageBox.Show(sLIKEClause)
    10.     End Sub
    You would then take that string (sLikeClause) and add it to your SQL
    Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim sString As String = "I love oat meal cookies"
            Dim sLIKEClause As String = String.Empty
            Dim arrString() As String = Split(sString, " ")
            sLIKEClause = "LIKE fieldname '%" & arrString(0).ToString & "%' "
            For i As Integer = 0 To arrString.Length - 1
                sLIKEClause = sLIKEClause & " OR fieldname LIKE '%" & arrString(i).ToString & "%' "
            Next
            Dim sql As String = "SELECT Indv_NAME As [Name in NIC] "
            sql = sql & "from(tbl_Indv) "
            sql = sql & "where Indv_NAME " & sLIKEClause
            MessageBox.Show(sql)
    End Sub

  10. #10

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Dear Hack

    This is a fabulous idea and it works like charm.Im so thankful to you for taking your time out to help me with this code.
    While enjoying your code the only issue I got was that now I get a huge number of results in the recordset and its not what I really want.
    Is there a way to append those words differently and then search again?
    Ex: I love oat meal cookies
    I love
    I oat
    I meal
    ....
    oat cookies

    You get the idea.
    Im so sorry for troubling you with a code which might not make sense to someone else but its really important that I figure this out.

    Hope you could help more

    Thank you

  11. #11

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Quote Originally Posted by SeanGrebey View Post
    Use strA.Length - 1 to find the index of the last word instead of assuming 1.
    Thank you sir for replying

    I already have a code written to get the last three words of a string and jumble the words in one way.

    Code:
    Dim str As String = Me.t1.Text
    
            Dim strA() As String = str.Split(" ")
    
            If strA.Length > 2 Then
                Dim a As String = (strA(strA.Length - 3) + " " + strA(strA.Length - 2) + " " + strA(strA.Length - 1))
                Dim a2() As String = a.Split(" ")
                Dim ne(100) As String
                ne(0) = a2(1)
                ne(1) = a2(2)
                ne(2) = a2(0)
                MessageBox.Show(ne(0) + " " + ne(1) + " " + ne(2))
            End If
    I know it is not a very good code.Pardon my coding knowledge.
    I want a code that does the above procedure no matter how many words are entered.I want to get the maximum number of results.Like with 3 words I should get 6 possible strings

  12. #12
    Frenzied Member
    Join Date
    Mar 2004
    Location
    Orlando, FL
    Posts
    1,618

    Re: Swap words in a string

    Where you are doing this:

    Code:
                Dim ne(100) As String
                ne(0) = a2(1)
                ne(1) = a2(2)
                ne(2) = a2(0)
                MessageBox.Show(ne(0) + " " + ne(1) + " " + ne(2))
    Do loops instead:

    Code:
    For intI as integer = 0 to a2.Length - 2
      ne(intI) = a2(intI+1)
    Next
    
    ' Get the last one
    ne(a2.Length - 1) = a2(0)
    
    Dim strOutput as String
    
    For intI as integer = 0 to a2.Length - 1
      strOutput = strOutput  + ne(intI) + " " 
    Next
    
    ' SHow and remove trailign space
    MessageBox.Show(Trim(strOutput))
    That's just quick and dirty, can probably be cleaned up, but you get the idea.
    Sean

    Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.

  13. #13

    Thread Starter
    Member
    Join Date
    Oct 2011
    Location
    Sri Lanka
    Posts
    40

    Re: Swap words in a string

    Dear Hack and Sean

    Thank you both for taking your time and suggesting ways to find a solution for my case.I really appreciate it.
    I have finally found a method which will give all the possible permutations for combinations of words in a string.Hers is the code I found.And all the credit should go to a gentlemen named LanFanNinja.He used Heap's alogorithm for this.

    Code:
    Private Sub Form1_Load(sender As Object, e As EventArgs)
        Dim word As String = "I like cake"
        Dim split As String() = word.Split(New Char() {" "c}, 
            StringSplitOptions.RemoveEmptyEntries)
        Dim words As New List(Of String)()
     
        HeapPermute(words, split, split.Length)
     
        ' "words" now contains all possible permutations of "word"
    End Sub
     
    Private Sub HeapPermute(words As List(Of String), split As String(), splitCount As Integer)
        Dim n As Integer = splitCount
     
        If n = 1 Then
            'add item
            Dim temp As String = ""
            For i As Integer = 0 To split.Length - 1
                temp += split(i) & " "
            Next
            words.Add(temp.TrimEnd(" "c))
        Else
            For i As Integer = 0 To n - 1
                HeapPermute(words, split, (n - 1))
                If n Mod 2 = 1 Then
                    'odd
                    Dim temp As String = split(0)
                    split(0) = split(n - 1)
                    split(n - 1) = temp
                Else
                    'even
                    Dim temp As String = split(i)
                    split(i) = split(n - 1)
                    split(n - 1) = temp
                End If
            Next
        End If
    End Sub
    This code will provide this outcome

    Code:
    I like cake
    like I cake
    cake I like
    I cake like
    like cake I
    cake like I
    If you can please suggest any improvements.

    Thank you
    Last edited by chathu1234; Nov 30th, 2011 at 06:55 AM. Reason: Forgot to input output of the code

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