如何使用 Mid 和 Len 在字符串的开头、中间和结尾添加一个字符?

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

高中的作业class,我试了很多东西,查了很多东西,就是做不出来!任务是制作一个神奇的词,无论用户想要什么。这很混乱,但我想学习!任何建议都会很棒!我已经尝试了下面代码中的内容,但我不知道如何指定将它添加到标签的开头,分配是有一个标签,并且有能够在文本框中添加字符的按钮到标签的开头、中间和结尾。这是星期三 10 月 20 日到期的,因此,如果您对 visual basic 有所了解,我们将不胜感激。谢谢!

这是我试过的!它只向标签添加一次字符串的字符,但不会再次添加,这是我尝试添加到 beginning 但尚未尝试添加到中间和结束。

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

问题就出在这里

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

你在这里所做的是将 3 次写入同一个变量 NewString 所以最后只有最后一个值 NewString = MagicLetter.Insert(1, 0) 在变量中,因为之前的 2 被下一个覆盖了.因此,如果您删除前 2 行,这三行仍然会执行相同的操作。

那你就不需要任何全局变量了:

Dim MagicLetter As String
Dim NewString As String

您可以在 Button1_Click 过程中使用局部变量来完成。如果可以,请始终使用局部变量而不是全局变量。

您也不需要 TextBox1_TextChanged 事件,因为您对此文本框的 每次 更改不感兴趣。当你点击按钮时,你只想知道它的内容。

所以我们可以在Button1_Click过程中做所有事情

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
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

这也是设计器代码,因此您可以 copy/paste buttons/textbox/labels。

访问设计背后的代码的方法如下: 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
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

magicWord = "abcdefg"(奇数个字符)时,

1abc1defg1

插入的字符串不太在中间,但是你的问题要求不明确

这不包括验证,例如 TextBox.Text 应该是一个字符,并且魔术字长度是奇数或偶数。整数除法\用于将整数个字符传递给TakeSkip.

这可能无法使用,因为它不使用 MidLen,但我将其发布以供后人使用

NewString = Len(Label2.Text)

你这里有问题 Len(String) returns 一个 Integer 并且你已经将 NewString 声明为 String。

NewString = Mid(MagicLetter, 1, 0)

在紧接着的下一行,您丢弃了 NewString 的值并分配了其他值。这有点傻,因为 Mid(string, StartIndex, Length) 因为长度为 0,这会得到你和空字符串。另一种令人困惑的方式是第二个参数 1。在 .net 中,事物的索引从 0 开始,但这个“索引”从 1 开始。让我们摆脱旧的 vb6 方法并使用 .net 改进。

NewString = MagicLetter.Insert(1, 0)

又是一个作业。 NewString 越来越累了。 .net 中 String 的一个有趣之处在于它是不可变的(无法更改)。在引擎盖下,每次字符串更改时,编译器都会丢弃旧字符串并创建一个全新的字符串。此行的另一个问题是 Insert 的第二个参数采用 String。 0 不是字符串,而是整数。

反斜杠表示整数除法。

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim MagicLetter As String = TextBox1.Text
    Dim MagicWord = "antiestablishmentarianism"
    Label1.Text = MagicWord & MagicLetter
    Label2.Text = MagicLetter & MagicWord
    Dim WordMiddle = MagicWord.Length \ 2
    Label3.Text = MagicWord.Insert(WordMiddle, MagicLetter)
End Sub