How to move the n word to the end of a string in VB.NET

1 Answer

0 votes
Imports System
Imports System.Linq
Imports System.Collections.Generic

Module Program

    Sub Main()
        Dim s As String = "Would you like to know more? (Explore and learn)"
        Dim n As Integer = 2

        Dim result As String = MoveNthWordToEndOfString(s, n)

        Console.WriteLine(result)
    End Sub


    Public Function MoveNthWordToEndOfString(input As String, n As Integer) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return input
        End If

        Dim parts As List(Of String) = input.Split({" "}, StringSplitOptions.RemoveEmptyEntries).ToList()

        ' Validate index
        If n < 0 OrElse n >= parts.Count Then
            Throw New ArgumentOutOfRangeException(NameOf(n), "Index is out of range.")
        End If

        Dim word As String = parts(n)
        parts.RemoveAt(n)
        parts.Add(word)

        Return String.Join(" ", parts)
    End Function

End Module



' run:
'
' Would you to know more? (Explore and learn) like
'

 



answered Feb 6 by avibootz
...