Reputation: 984
I have a text file from which I need to extract a block of text after the last instance of a specific string. To better ilustrate what is needed:
SpecificString#1:
TextBlock#1
SpecificString#2:
TextBlock#2
...
SpecificString#5:
TextBlock#5
All specific strings are identical, and the number of instances can vary. So far I am able to extract all TextBlocks after the first instance of the specific string with the following code:
const string separator = "SpecificString";
var separatorIndex = myTextFileString.IndexOf(separator, StringComparison.CurrentCultureIgnoreCase);
var requiredTextBlock = myTextFileString.Substring(separatorIndex + separator.Length);
However I would like to grab only the last block of text (TextBlock#5 in this case). How can I achieve this?
Upvotes: 1
Views: 208
Reputation: 511
Probably you should Read the text file differently. For instance:
string[] allLinesInText = File.ReadAllLines(path);
This returns each line in the text file as an array of string from which you can filter out the separators and index the blocks easily
const string separator = "SpecificString";
var allLines=allLinesInText.Where(x=>!x.Contains(separator));
If the text file contains a single string, you have to try the other answers proposed.
Upvotes: 1
Reputation: 44
You can get the last index of the separator in C# by using String.LastIndexOf()
method. Please take a look at https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof?view=netframework-4.8.
Once you know the last index, you can follow the same step as you have mentioned above to extract the text block after it.
Upvotes: 1