在单词中查找中间字符

时间:2012-09-24 03:05:56

标签: vb.net visual-studio-2010

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

1 个答案:

答案 0 :(得分:0)

我不确定你要做什么,但看看这是否适合你。它使用Mid方法从字符串中提取字符,使用Math.Round方法设置起始位置,并在长度+ 1上使用Mod将长度加1如果String.Length是偶数,则返回结果。


修改示例以添加函数并更好地解决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