Hi aginell4life,
First split the paragraph with space and loop through it.
Then, check the searched text index if found fetch the previous and next word with index value.
Finally, merge previos, searched and next text and insert in a list collection.
Refer below sample code.
HTML
<asp:Label ID="lblMessage" runat="server" />
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
string searchedText = "red";
string message = "I have a red cap in my bag. The color of my car is red blended with blue Could you lend me your red shirt.";
string[] words = message.Split(' ');
List<string> sentences = new List<string>();
for (int i = 0; i < words.Length; i++)
{
if (words[i].ToLower() == searchedText.ToLower())
{
string previous = string.Empty;
string next = string.Empty;
string previous1 = string.Empty;
string next1 = string.Empty;
if (i > 0)
{
previous = words[i - 1];
previous1 = words[i - 2];
}
if (i < words.Length - 1)
{
next = words[i + 1];
}
if (i < words.Length - 2)
{
next1 = words[i + 2];
}
sentences.Add(string.Format("{0} {1} {2} {3} {4}", previous1, previous, searchedText, next, next1));
}
}
lblMessage.Text = string.Join("<br />", sentences);
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim searchedText As String = "red"
Dim message As String = "I have a red cap in my bag. The color of my car is red blended with blue Could you lend me your red shirt."
Dim words As String() = message.Split(" "c)
Dim sentences As List(Of String) = New List(Of String)()
For i As Integer = 0 To words.Length - 1
If words(i).ToLower() = searchedText.ToLower() Then
Dim previous As String = String.Empty
Dim [next] As String = String.Empty
Dim previous1 As String = String.Empty
Dim next1 As String = String.Empty
If i > 0 Then
previous = words(i - 1)
previous1 = words(i - 2)
End If
If i < words.Length - 1 Then
[next] = words(i + 1)
End If
If i < words.Length - 2 Then
next1 = words(i + 2)
End If
sentences.Add(String.Format("{0} {1} {2} {3} {4}", previous1, previous, searchedText, [next], next1))
End If
Next
lblMessage.Text = String.Join("<br />", sentences)
End Sub
Screenshot