Home > Mobile >  How do I add a character to the beginning, middle, and end of a string using Mid and Len?
How do I add a character to the beginning, middle, and end of a string using Mid and Len?

Time:10-19

Its an assignment for a high school class, and I've tried so many things and looked up a lot of things, and just can't get it! The assignment is to make a magic word, whatever the user wants it to be. It's confusing but I want to learn! Any suggestions would be great! I have tried what is in the code below, but I don't know how to specify to add it to the beginning of a label, the assignment is to have a label, and have buttons that are able to add a character in a textbox to the beginning, middle, and end of a label. This is due wednesday 10/20, so please if you know anything about visual basic your help would be greatfully appreciated. thanks!

Here is what I have tried! It only adds a character of a string once to the label, but not again, this is the only code I tried to add to the beginning but have not yet tried to add to the middle and end.

Dim MagicLetter As String
Dim NewString As String
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    MagicLetter = TextBox1.Text
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    NewString = Len(Label2.Text)
    NewString = Mid(MagicLetter, 1, 0)
    NewString = MagicLetter.Insert(1, 0)
    If MagicLetter = TextBox1.Text Then
        NewString = Mid(MagicLetter, 1, 1)
    End If
    Label3.Text = "Magic Word: " & MagicLetter
    NewString = MagicLetter & Label2.Text

CodePudding user response:

The problem lies here

NewString = Len(Label2.Text)
NewString = Mid(MagicLetter, 1, 0)
NewString = MagicLetter.Insert(1, 0)

What you do here is you write 3 times into the same variable NewString so in the end only the last value NewString = MagicLetter.Insert(1, 0) is in the variable because the 2 before got overwritten by the next one. So these three lines still do the same if you delete the first 2.

Then you don't need any global variables:

Dim MagicLetter As String
Dim NewString As String

You can do it with local variables inside the Button1_Click procedure. Always use local variables over global ones if you can.

Also you don't need the TextBox1_TextChanged event because you are not interested in every change of this text box. You only want to know its content when you click the button.

So we can do everything in the Button1_Click procedure

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim OriginalText As String
    OriginalText = Label3.Text  ' here we get the text from the label

    Dim MagicLetter As String
    MagicLetter = TextBox1.Text  ' here we get the magic letter from the textbox

    Dim NewText As String
    NewText = OriginalText  ' our new text should be created from the original text


    ' now we add the magic letter infront
    NewText = MagicLetter & NewText 


    ' now we add the magic letter in the end
    NewText = NewText & MagicLetter


    ' now we add the magic letter in the middle
    Dim TextLength As Long
    TextLength = Len(NewText)  ' here we get the length of our text (we need to split it in the middle)

    Dim LeftPart As String
    LeftPart = Mid(NewText, 1, CLng(TextLength / 2))  ' here we get the left part of the text

    Dim RightPart As String
    RightPart = Mid(NewText, Len(LeftPart)   1)   ' here we get the right part of the text

    ' now we add the magic letter between the left and right part
    NewText = LeftPart & MagicLetter & RightPart

   
    ' finall we write the new text into our label
    Label3.Text = NewText
End Sub

CodePudding user response:

Public Class FormMagicWord
    Private Function GenerateMagicWord(MagicLetter As Char, Type As String)
        'Declare the MagicWord as the label, which is set as just "Magic" in the designer
        Dim MagicWord As String = LblMagicWord.Text

        'Use a case statement (which is just a cleaner if/else if/else)
        Select Case Type
            Case "Beginning"
                'Combine the MagicLetter and the MagicWord into the MagicWord string.
                MagicWord = MagicLetter & MagicWord
            Case "Middle"
                'Set the initial "midpoint" as 0 in-case the label is empty.
                Dim MidPoint As Integer = 0

                'Get the middle of the MagicWord string if its length > 0.  I used Math.Floor() which will round down to the nearest whole number, so if the length was 9:  9/2 = 4.5 it would round down to 4.
                'Alternatively you can use Math.Ceiling() which does the opposite, it rounds up to the next whole number, so if the length was 9:  9/2 = 4.5 it would round up to 5.
                'It's cast as an integer (CInt) because we only care about whole numbers for this
                If MagicWord.Length > 0 Then
                    MidPoint = CInt(Math.Floor(MagicWord.Length / 2))
                End If

                'Insert the MagicLetter at the midpoint of the MagicWord string.
                MagicWord = MagicWord.Insert(MidPoint, MagicLetter)
            Case "End"
                'Combine the MagicWord and the MagicLetter into the MagicWord string.
                MagicWord = MagicWord & MagicLetter
            Case Else
                'Not used, but this would be the "else" equivalent for a Select/Case/Switch statement
        End Select

        'Return the MagicWord string
        Return MagicWord

    End Function

    'I've changed the handler to manage all three buttons: (BtnBeginning, BtnMiddle, BtnEnd) because the logic is the same for all of them. 
    'I've also changed the default sender object to Btn as a button, so it explicitly knows what type of control we're handling
    Private Sub BtnBeginning_Click(Btn As Button, e As EventArgs) Handles BtnBeginning.Click, BtnMiddle.Click, BtnEnd.Click
        'Get the magic letter as a single character, which is all we need.
        'The designer also has the max length of the TxtMagicLetter textbox set to 1
        Dim MagicLetter As Char = TxtMagicLetter.Text

        'Call the GenerateMagicWord function passing the arguments of the letter and the text of the button (Beginning, Middle, End) which will run through the select statement to determine how to format the string
        Dim MagicWord As String = GenerateMagicWord(MagicLetter, Btn.Text)

        'Finally, set the MagicWord label as the returned string
        LblMagicWord.Text = MagicWord
    End Sub
End Class

Here's the designer code as well so you can just copy/paste the buttons/textbox/labels.

Here's how to access the code behind the design: View Designer Code in Visual Studio 2010

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FormMagicWord
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    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.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.TxtMagicLetter = New System.Windows.Forms.TextBox()
        Me.BtnBeginning = New System.Windows.Forms.Button()
        Me.BtnMiddle = New System.Windows.Forms.Button()
        Me.BtnEnd = New System.Windows.Forms.Button()
        Me.LbLMagicLetter = New System.Windows.Forms.Label()
        Me.LblMagicWordLabel = New System.Windows.Forms.Label()
        Me.LblMagicWord = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        '
        'TxtMagicLetter
        '
        Me.TxtMagicLetter.Location = New System.Drawing.Point(249, 12)
        Me.TxtMagicLetter.MaxLength = 1
        Me.TxtMagicLetter.Name = "TxtMagicLetter"
        Me.TxtMagicLetter.Size = New System.Drawing.Size(246, 20)
        Me.TxtMagicLetter.TabIndex = 0
        '
        'BtnBeginning
        '
        Me.BtnBeginning.Location = New System.Drawing.Point(12, 38)
        Me.BtnBeginning.Name = "BtnBeginning"
        Me.BtnBeginning.Size = New System.Drawing.Size(157, 33)
        Me.BtnBeginning.TabIndex = 1
        Me.BtnBeginning.Text = "Beginning"
        Me.BtnBeginning.UseVisualStyleBackColor = True
        '
        'BtnMiddle
        '
        Me.BtnMiddle.Location = New System.Drawing.Point(175, 38)
        Me.BtnMiddle.Name = "BtnMiddle"
        Me.BtnMiddle.Size = New System.Drawing.Size(157, 33)
        Me.BtnMiddle.TabIndex = 2
        Me.BtnMiddle.Text = "Middle"
        Me.BtnMiddle.UseVisualStyleBackColor = True
        '
        'BtnEnd
        '
        Me.BtnEnd.Location = New System.Drawing.Point(338, 38)
        Me.BtnEnd.Name = "BtnEnd"
        Me.BtnEnd.Size = New System.Drawing.Size(157, 33)
        Me.BtnEnd.TabIndex = 3
        Me.BtnEnd.Text = "End"
        Me.BtnEnd.UseVisualStyleBackColor = True
        '
        'LbLMagicLetter
        '
        Me.LbLMagicLetter.AutoSize = True
        Me.LbLMagicLetter.Location = New System.Drawing.Point(172, 12)
        Me.LbLMagicLetter.Name = "LbLMagicLetter"
        Me.LbLMagicLetter.Size = New System.Drawing.Size(66, 13)
        Me.LbLMagicLetter.TabIndex = 4
        Me.LbLMagicLetter.Text = "Magic Letter"
        '
        'LblMagicWordLabel
        '
        Me.LblMagicWordLabel.AutoSize = True
        Me.LblMagicWordLabel.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.LblMagicWordLabel.Location = New System.Drawing.Point(8, 141)
        Me.LblMagicWordLabel.Name = "LblMagicWordLabel"
        Me.LblMagicWordLabel.Size = New System.Drawing.Size(112, 24)
        Me.LblMagicWordLabel.TabIndex = 5
        Me.LblMagicWordLabel.Text = "Magic Word"
        '
        'LblMagicWord
        '
        Me.LblMagicWord.AutoSize = True
        Me.LblMagicWord.Font = New System.Drawing.Font("Microsoft Sans Serif", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.LblMagicWord.Location = New System.Drawing.Point(135, 141)
        Me.LblMagicWord.Name = "LblMagicWord"
        Me.LblMagicWord.Size = New System.Drawing.Size(0, 24)
        Me.LblMagicWord.TabIndex = 6
        Me.LblMagicWord.Text = "Magic"
        '
        'FormMagicWord
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(800, 450)
        Me.Controls.Add(Me.LblMagicWord)
        Me.Controls.Add(Me.LblMagicWordLabel)
        Me.Controls.Add(Me.LbLMagicLetter)
        Me.Controls.Add(Me.BtnEnd)
        Me.Controls.Add(Me.BtnMiddle)
        Me.Controls.Add(Me.BtnBeginning)
        Me.Controls.Add(Me.TxtMagicLetter)
        Me.Name = "FormMagicWord"
        Me.Text = "Magic Word"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Friend WithEvents TxtMagicLetter As TextBox
    Friend WithEvents BtnBeginning As Button
    Friend WithEvents BtnMiddle As Button
    Friend WithEvents BtnEnd As Button
    Friend WithEvents LbLMagicLetter As Label
    Friend WithEvents LblMagicWordLabel As Label
    Friend WithEvents LblMagicWord As Label
End Class

CodePudding user response:

Dim magicWord As String = "abcdef"
Label1.Text = $"{TextBox1.Text}{String.Concat(magicWord.Take(magicWord.Length \ 2))}{TextBox1.Text}{String.Concat(magicWord.Skip(magicWord.Length \ 2))}{TextBox1.Text}"

1abc1def1

When magicWord = "abcdefg" (odd number of characters),

1abc1defg1

the inserted string is not quite in the middle, but the requirement is not clear in your question.

This doesn't include validation such as TextBox.Text should be a char, and magic word length being odd or even. Integer division \ is used to pass an integral number of characters to Take and Skip.

This may not be usable since it doesn't utilize Mid or Len, but I posted it for posterity

  • Related