How to get a word by index in C# and VB.NET

To get a word by index in C# and VB.NET you can use the following snippet.

Sample C#

public static string GetWordByIndex(string input, int index)
{
	try
	{
		var words = input.Split(' ');
		if ((index < 0) || (index > words.Length - 1))
		{
			throw new IndexOutOfRangeException("Index out of range!");
		}
		return words[index];
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return string.Empty;
	}
}

Sample VB.NET

Public Shared Function GetWordByIndex(input As String, index As Integer) As String
	Try
		Dim words = input.Split(" ")
		If (index < 0) OrElse (index > words.Length - 1) Then
			Throw New IndexOutOfRangeException("Index out of range!")
		End If
		Return words(index)
	Catch ex As Exception
		'handle the exception your way
		Return String.Empty
	End Try
End Function

One thought on “How to get a word by index in C# and VB.NET

Leave a Reply