/// <summary> /// Extract a substring. /// </summary> /// <param name="startIndex">Index to start from.</param> /// <param name="length">Count of characters to extract.</param> /// <returns>The substring.</returns> public IString Substring(int startIndex, int length) { var currentIndex = 0; var lengthLeft = length; var builder = new ColoredMultistringBuilder(); foreach (var piece in Content) { if (currentIndex + piece.Length <= startIndex) { // Do nothing. } else { var offsetIntoPiece = (startIndex <= currentIndex) ? 0 : startIndex - currentIndex; var charsToCopy = Math.Min(lengthLeft, piece.Length - offsetIntoPiece); Debug.Assert(charsToCopy > 0); if (charsToCopy == piece.Length) { builder.Append(piece); } else { builder.Append(piece.Substring(offsetIntoPiece, charsToCopy)); } lengthLeft -= charsToCopy; Debug.Assert(lengthLeft >= 0); if (lengthLeft == 0) { break; } } currentIndex += piece.Length; } if (lengthLeft > 0) { throw new IndexOutOfRangeException($"Invalid substring extraction"); } return(builder.ToMultistring()); }
/// <summary> /// Split the string by the indicated separator. /// </summary> /// <param name="separator">Separator for splitting.</param> /// <param name="options">Split options.</param> /// <returns>The split pieces of the string.</returns> public IEnumerable <IString> Split(char separator, StringSplitOptions options = StringSplitOptions.None) { ColoredMultistringBuilder builder = null; foreach (var piece in Content) { var s = piece.Content; int index; while ((index = s.IndexOf(separator)) >= 0) { if (index > 0 || (index == 0 && options == StringSplitOptions.None)) { if (builder == null) { builder = new ColoredMultistringBuilder(); } var firstPart = s.Substring(0, index); builder.Append(piece.WithContent(firstPart)); yield return(builder.ToMultistring()); builder = null; } s = s.Substring(index + 1); } if (!string.IsNullOrEmpty(s)) { if (builder == null) { builder = new ColoredMultistringBuilder(); } builder.Append(piece.WithContent(s)); } } if (builder != null) { yield return(builder.ToMultistring()); } }