Sample code - split string and create a list of lists

CSharp · Console

/Program.cs

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		string sample = "<h1>Title 1</h1>" + "Article text1" + "<h1>Title 2</h1>" + "Article text2" + "<h1>Title 3</h1>" + "Article text3";
		// string.split - by multiple character delimiter
		// Credit: https://stackoverflow.com/a/1254596/12511801
		string[] arr = sample.Split(new string[]{"</h1>"}, StringSplitOptions.None);
		
		// I store the "title" and "article" in separated lists - their content will be unified later:
		List<string> titles = new List<string>();
		List<string> articles = new List<string>();
		
		// Loop the splitted text by "</h1>": 
		foreach (string s in arr)
		{
			if (s.StartsWith("<h1>"))
			{
				titles.Add(s.Split(new string[]{"<h1>"}, StringSplitOptions.None)[1]);
			}
			else
			{
				if (s.Contains("<h1>"))
				{
					// Position 0 is the article and the 1 position is the title: 
					articles.Add(s.Split(new string[]{"<h1>"}, StringSplitOptions.None)[0]);
					titles.Add(s.Split(new string[]{"<h1>"}, StringSplitOptions.None)[1]);
				}
				else
				{
					// Leading text - it's an article by default.
					articles.Add(s.Split(new string[]{"<h1>"}, StringSplitOptions.None)[0]);
				}
			}
		}

		/*
		
		// NOTE: Printing the current results in the individual lists.
		
		Console.WriteLine("Amount of titles: " + titles.Count.ToString());
		foreach (string t in titles)
		{
			Console.WriteLine("Title: " + t);
		}

		Console.WriteLine("Amount of articles: " + articles.Count.ToString());
		foreach (string a in articles)
		{
			Console.WriteLine("Article: " + a);
		}
		*/
		
		// ------------
		// Create a list of lists.
		// Credit: https://stackoverflow.com/a/12628275/12511801
		List<List<string>> myList = new List<List<string>>();
		for (int i = 0; i < titles.Count; i++)
		{
			myList.Add(new List<string>{"Title: " + titles[i], "Article: " + articles[i]});
		}

		// Print the results: 
		foreach (List<string> subList in myList)
		{
			foreach (string item in subList)
			{
				Console.WriteLine(item);
			}
		}
	}
}
;