How to get the original sentence from a sentences by knowing an offset of a word in C#

Viewed 40

suppose string is "This is very amazing platform in the world"

I have 2 words First and Last Words with offset value like First word "very" second Word "Platform"

and this output is expected "very amazing platform"

can anyone help how to DO?

1 Answers

You could use the string IndexOf() method to find the index position of a certain string, an then use the indexes with Substring() to extract a part of the original string.

string str = "This is very amazing platform in the world";

string firstWord = "very";
string lastWord = "platform";

// Find the index position of the first letter in the first word
int startIndex = str.IndexOf(firstWord, StringComparison.OrdinalIgnoreCase);
// Find the index position of the first letter in the last word, and add the length of the word
int endIndex = str.LastIndexOf(lastWord, StringComparison.OrdinalIgnoreCase) + lastWord.Length;

// Substring the original string, from start index and for the length up to the end index
string res = str.Substring(startIndex, endIndex - startIndex);
Related