2012-09-24 75 views
0

如何在不使用if else語句的情況下在Visual Basic中找到單詞中的中間字符?例如,我在文本框中輸入STRENGTH一詞,當我點擊按鈕時,我應該在文本框中輸入EN。如果我把SOS放入文本框中,我應該在文本框中輸入O.查找單詞中的中間字符

+0

你的問題有點不清楚。請在提問時嘗試具體說明,請參閱[faq](http://stackoverflow.com/faq#howtoask)。 –

回答

0

我不確定你想要做什麼,但看看這是否適合你。它使用Mid方法從字符串中拉出字符,並使用Math.Round方法設置起始位置,如果String.Length爲偶數,則在Length + 1上使用Mod將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 
相關問題