How to remove the middle word from a string in VB.NET

1 Answer

0 votes
Imports System
Imports System.Linq

Module RemoveMiddleWordFromString
    Sub Main()
        Dim str As String = "c# c c++ java rust"

        Dim result As String = RemoveMiddleWord(str)

        Console.WriteLine(result)
    End Sub

    Function RemoveMiddleWord(input As String) As String
        ' Split the string into words
        Dim words = input.Split({" "}, StringSplitOptions.RemoveEmptyEntries)

        ' If there are fewer than 3 words, nothing to remove
        If words.Length <= 2 Then
            Return input
        End If

        ' Calculate the middle index
        Dim midIndex As Integer = words.Length \ 2   ' integer division

        ' Remove the middle word
        Dim result = String.Join(" ",
            words.Take(midIndex).Concat(words.Skip(midIndex + 1)))

        Return result
    End Function
End Module

	

' run:
'
' c# c java rust
'

 



answered Dec 3, 2024 by avibootz
edited Dec 24, 2025 by avibootz
...