0

在不使用 if else 语句的情况下,如何在 Visual Basic 中找到单词中的中间字符?例如,我在文本框中输入单词 STRENGTH,当我单击按钮时,我应该在文本框中输入 EN。如果我将 SOS 放入文本框中,我应该在文本框中输入 O。

4

1 回答 1

0

我不确定您要做什么,但看看这是否适合您。它使用MidMethod 从字符串中提取字符,使用Math.RoundMethod 设置起始位置,Mod如果 String.Length 为偶数,则使用 Length + 1 将返回结果的 Length 加 1。


修改示例以添加功能并更好地解决 OP 的问题。

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        TextBox2.Text = middleOfString(TextBox1.Text)
    End Sub

    Private Function middleOfString(value As String) As String

        'Get start location of substring, if value.length is odd have we have to make sure the result of the division rounds up to the nearest integer
        Dim start As Integer = CInt(Math.Round(value.Length / 2, MidpointRounding.AwayFromZero))

        'Get length of substring 1 if value length is odd, 2 if value length is even
        Dim length As Integer = CInt((value.Length + 1) Mod 2) + 1

        Return Mid(value, start, length)

    End Function

End Class
于 2012-09-24T06:27:57.770 回答