Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace SplitWithDelimiter
- {
- internal static class Program
- {
- internal static void Main()
- {
- const bool addEmptyStrings = false;
- Display(MySplit1("Hello****wide****world", "****", addEmptyStrings));
- Display(MySplit1("Hello****wide****world****", "****", addEmptyStrings));
- Display(MySplit1("****Hello****wide********world", "****", addEmptyStrings));
- Display(MySplit2("Hello****wide****world", "****", addEmptyStrings));
- Display(MySplit2("Hello****wide****world****", "****", addEmptyStrings));
- Display(MySplit2("****Hello****wide********world", "****", addEmptyStrings));
- }
- private static void Display(IEnumerable<string> enumerable)
- {
- foreach (string item in enumerable)
- {
- Console.WriteLine(" - '" + item + "'");
- }
- Console.WriteLine();
- Console.WriteLine();
- }
- private static IEnumerable<string> MySplit1(string text, string delimiter, bool addEmptyStrings)
- {
- Console.WriteLine("Split: '" + text + "'");
- string updated = text.Replace(delimiter, "\x1\x2" + delimiter + "\x1\x2");
- if (!addEmptyStrings)
- {
- updated = updated.Replace("\x1\x2\x1\x2", "\x1\x2");
- if (updated.StartsWith("\x1\x2", StringComparison.Ordinal))
- {
- updated = updated.Remove(0, 2);
- }
- if (updated.EndsWith("\x1\x2", StringComparison.Ordinal))
- {
- updated = updated.Substring(0, updated.Length - 2);
- }
- }
- return (updated.Split(new[] { "\x1\x2" }, StringSplitOptions.None));
- }
- private static IEnumerable<string> MySplit2(string text, string delimiter, bool addEmptyStrings)
- {
- Console.WriteLine("Split: '" + text + "'");
- List<string> result = new List<string>(5);
- int previous = 0;
- while (previous < text.Length)
- {
- int next = text.IndexOf(delimiter, previous);
- if (next < 0)
- {
- result.Add(text.Substring(previous));
- return (result);
- }
- int length = (next - previous);
- if (length > 0 || addEmptyStrings)
- {
- result.Add(text.Substring(previous, next - previous));
- }
- result.Add(delimiter);
- previous = (next + delimiter.Length);
- }
- if (addEmptyStrings)
- {
- result.Add("");
- }
- return (result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement