Solved

Replace Text in a string (VB.Net)

Posted on 2004-04-14
26
3,008 Views
Last Modified: 2008-02-07
I would like to replace text in a string submitted from a RichTextBox.  Ideally i would like to replace the text with an image, for example: if i was to type :) then a smiley image would appear in its place.  the text submitted from the RichTextBox is displayed in another RichTextBox (like a chat program basically)

Language: VB.Net
0
Comment
Question by:TheMadMonkey
  • 12
  • 7
  • 4
  • +2
26 Comments
 
LVL 11

Expert Comment

by:L00M
ID: 10825479
...
Dim myStr as String = "Hello :)"

rtb1.Text = ReplaceEmoticons(myStr)
...


Function ReplaceEmoticons(byval str as string) as String
  str = Replace(str, ":)", "<img src='images/smiley.jpg'>")
  str = Replace(str, ":(", "<img src='images/frown.jpg'>")
  '...
  Return str
End Function

Like that?
0
 
LVL 11

Expert Comment

by:L00M
ID: 10825496
hmmmm, I think not. You need to convert the emoticon to a picture object instead eh? (I was thinking html....sorry)
0
 

Author Comment

by:TheMadMonkey
ID: 10825522
yes each emoticon will be a picture object that needs to be insterted when a user types :) or :P etc (not directly in the box they are typing in, just the output box which is where the chat is displayed)

Thanks
0
 
LVL 9

Expert Comment

by:malharone
ID: 10825713
i'd recommend storing the text as HTML then RTF .. since HTML is easier to parse/analyze. plus by "linking" images in HTML you'd save space by not embedding them into RTF
0
 

Author Comment

by:TheMadMonkey
ID: 10825752
storing the images aren't my concern, its getting them to display in the RichTextBox when a user types :) or :P for example.
0
 

Author Comment

by:TheMadMonkey
ID: 10825763
EDIT:  i will not be linking the images from anywhere, the images will be stored as picture objects
0
 
LVL 9

Expert Comment

by:malharone
ID: 10825822
ok...
1) load all the different images in an ImageList -- an array of image or a hashtable
2) set key-preview property to TRUE. and add an event for key-preview. so when you detect user typed the pattern ":)" or ":("  --- in two consecutive evnets, find the appropriate image from the list. Copy it to the clipboard (clipboard.copy) .. and then paste it into the richtextbox (richtbox1.Paste()).


hope this helps
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 10826048
This is basically what malharone said.

Obviously, the code below could be made far more efficient than what it is but it demonstrates the concept.

I placed three gifs [smiley.gif, wink.gif, sad.gif] in the \bin directory.

Idle_Mind

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private emoticons As New Collection

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim img As Image
        Dim curdir As String = Environment.CurrentDirectory & "\"

        If System.IO.File.Exists(curdir & "smiley.gif") Then
            img = Image.FromFile(curdir & "smiley.gif")
            emoticons.Add(img, "smiley")
        End If
        If System.IO.File.Exists(curdir & "wink.gif") Then
            img = Image.FromFile(curdir & "wink.gif")
            emoticons.Add(img, "wink")
        End If
        If System.IO.File.Exists(curdir & "sad.gif") Then
            img = Image.FromFile(curdir & "sad.gif")
            emoticons.Add(img, "sad")
        End If
    End Sub

    Private Sub RichTextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
        Dim plainText As String
        Dim currentLoc As Integer

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ":)")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("smiley"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ";)")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("wink"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ":(")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("sad"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0
    End Sub
End Class

0
 

Author Comment

by:TheMadMonkey
ID: 10826354
well thats SORT of what i want.    all i want is something that will read a string of text and replace words, like "this is cool"   if i want to replace all "is" words that appear in the string to "was", how would i go about doing such a thing?


same concept with inserting the emoticons.   because i want the images to pull from client side, i dont want huge chunks of bytes being transfered from client to server and broadcasted to the other connected clients in the chat and etc.

hope that clears some things up.

Thanks


0
 
LVL 22

Expert Comment

by:_TAD_
ID: 10826372


** Not for Points **

Just a quick note: I like the idea.  Personally, I would not put all of the icons/gifs into a directory.  Instead I would create a resx (resource) file that I would read from (and store in an image list, etc, etc).  This will prevent the users from altering your images.  Also, this allows you to have future graphic enhancements with a simple change of a resx file.

Just a thought...
0
 

Author Comment

by:TheMadMonkey
ID: 10826390
good idea, TAD, thanks.
0
 
LVL 9

Expert Comment

by:malharone
ID: 10826399
Yes .. _TAD_ is correct. RESX files are the best approach for storing internal resources.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 10826644
All true.  My example replaces the text in real time, but you could just as easily send the text across your connection, place it into a richtextbox, and then use code similar to what I posted to replace it after it has been received.

Incidentally, here is how you would replace all occurences of "is" with "was"

    RichTextBox1.Rtf = RichTextBox1.Rtf.Replace("is", "was")

Regards,

Idle_Mind
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:TheMadMonkey
ID: 10826683
Thank You!  that works for replacing text, now all i need is to get it to change :) text to smiley image

0
 

Author Comment

by:TheMadMonkey
ID: 10826966
EDIT:  this is a 500 point question.  i'm a newbie to VB.Net so please make the solution as simple as possible for me.  I have not found my solution yet so the question still stands.

Thank You

0
 
LVL 9

Expert Comment

by:malharone
ID: 10827166
ok... how about this .. you can insert ":(", ":)" , ":-", ":|"

you must first make sure you use proper images.

Public Class Form9
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.RichTextBox1 = New System.Windows.Forms.RichTextBox
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'RichTextBox1
        '
        Me.RichTextBox1.Location = New System.Drawing.Point(16, 8)
        Me.RichTextBox1.Name = "RichTextBox1"
        Me.RichTextBox1.Size = New System.Drawing.Size(328, 264)
        Me.RichTextBox1.TabIndex = 0
        Me.RichTextBox1.Text = ""
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(16, 280)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(280, 20)
        Me.TextBox1.TabIndex = 1
        Me.TextBox1.Text = "TextBox1"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(304, 280)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(40, 23)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "Send"
        '
        'Form9
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(536, 405)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.RichTextBox1)
        Me.Name = "Form9"
        Me.Text = "Form9"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With il.Images
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\areatool.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\attach.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\perimeter.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\selecttext.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\snapshot.gif"))
        End With
    End Sub

    Private Function getImage(ByVal st As String) As Image
        Select Case st
            Case ":)"
                Return il.Images(0)
            Case ":("
                Return il.Images(1)
            Case ":-"
                Return il.Images(2)
            Case Else
                Return il.Images(3)
        End Select
    End Function
    Dim il As New ImageList

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Me.RichTextBox1.Text += "aaa"
        Dim txt As String = Me.TextBox1.Text
        Dim ch As Char
        Dim chs() As Char = txt.ToCharArray()
        Dim x As Integer
        For x = 0 To chs.Length - 1
            ch = chs(x)
            If chs(x) = ":" AndAlso (x + 1 < chs.Length) Then
                If (chs(x + 1) = ")" OrElse chs(x + 1) = "(" OrElse chs(x + 1) = "-" OrElse chs(x + 1) = "|") Then
                    Dim i As Image = getImage(ch & chs(x + 1))
                    Clipboard.SetDataObject(i)
                    x += 1
                    Me.RichTextBox1.Paste()
                Else
                    Me.RichTextBox1.AppendText(ch)
                End If
            Else
                Me.RichTextBox1.AppendText(ch)
            End If
        Next
        Me.TextBox1.Text = ""
    End Sub
End Class
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 10827773
TheMadMonkey,

The code I already posted shows you to change :) to a smiley face.

What part don't you understand?

Idle_Mind
0
 

Author Comment

by:TheMadMonkey
ID: 10827809
read my comments and you'll find out
0
 

Author Comment

by:TheMadMonkey
ID: 10827967
malharone, your code works great!  only problem is the image backgrounds show up blue and are resizeable in the RTF box :(  any idea's to get images to show properly?  i know, i'm picky, but hey, if you can help me figure this small part out, 500 points are all yours.

Thanks
0
 

Author Comment

by:TheMadMonkey
ID: 10828021
EDIT: oh and i noticed the emoticons dont show up when the RichTextBox is set to readonly, which is a problem because i want it to be readonly lol.
0
 
LVL 9

Expert Comment

by:malharone
ID: 10828028
yes .. because paste is "interactive" .. not programmatic.
0
 
LVL 9

Accepted Solution

by:
malharone earned 500 total points
ID: 10828107
well .. this is not foolproof .. but certainly a step forward .. basically i'm setting focus when user tries to do something in RTbox.
i'm also setting readonly off before inserting and on after inserting the icon.
But as you may realize, the "readonly" is buggy. It still lets you resize the image. I'm sure M$'d claim it's a feature -- not a bug.

- malhar


    Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With il.Images
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\areatool.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\attach.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\perimeter.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\selecttext.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\snapshot.gif"))
        End With
    End Sub

    Private Function getImage(ByVal st As String) As Image
        Select Case st
            Case ":)"
                Return il.Images(0)
            Case ":("
                Return il.Images(1)
            Case ":-"
                Return il.Images(2)
            Case Else
                Return il.Images(3)
        End Select
    End Function
    Dim il As New ImageList

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Me.RichTextBox1.Text += "aaa"
        Me.RichTextBox1.ReadOnly = False
        Dim txt As String = Me.TextBox1.Text
        Dim ch As Char
        Dim chs() As Char = txt.ToCharArray()
        Dim x As Integer
        For x = 0 To chs.Length - 1
            ch = chs(x)
            If chs(x) = ":" AndAlso (x + 1 < chs.Length) Then
                If (chs(x + 1) = ")" OrElse chs(x + 1) = "(" OrElse chs(x + 1) = "-" OrElse chs(x + 1) = "|") Then
                    Dim i As Image = getImage(ch & chs(x + 1))
                    Clipboard.SetDataObject(i)
                    x += 1
                    Me.RichTextBox1.Paste()
                Else
                    Me.RichTextBox1.AppendText(ch)
                End If
            Else
                Me.RichTextBox1.AppendText(ch)
            End If
        Next
        Me.RichTextBox1.AppendText(vbCrLf)
        Me.TextBox1.Text = ""
        Me.RichTextBox1.ReadOnly = True
    End Sub

    Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged
        Me.RichTextBox1.Select(Me.RichTextBox1.Text.Length, 0)
    End Sub

    Private Sub RichTextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.GotFocus
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Enter
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Click
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDown
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_ContentsResized(ByVal sender As Object, ByVal e As System.Windows.Forms.ContentsResizedEventArgs) Handles RichTextBox1.ContentsResized
        Me.TextBox1.Focus()
    End Sub
0
 

Author Comment

by:TheMadMonkey
ID: 10828127
Thanks for all of your help!
0
 
LVL 9

Expert Comment

by:malharone
ID: 10828148
glad to help.
i was just searching google and found exactly what you're lookign for..

http://www.codeproject.com/cs/miscctrl/csexrichtextbox.asp

however even this does not solve image resize problem.

- malhar
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 10828187
No disrespect meant to TheMadMonkey or malharone or anyone else in this thread but did you not look at my code?  It does essentially the same thing.  It places an Image on the clipboard, selects text in a richtextbox and then pastes the image over the selected text.

Anyhoo...

Good Luck to All

Idle_Mind
0
 

Author Comment

by:TheMadMonkey
ID: 10828250
your code is nice and all, but it would not compile for me.

sorry :(
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now