Mega Code Archive

 
Categories / C# / File Stream
 

Returns the zero-based line number where source appears in target

using System.Globalization; using System.Linq; using System.Text; namespace jQueryBuddy.Utilities {     public static class StringExtensions     {         /// <summary>         /// Returns the zero-based line number where <paramref name="source"/>         /// appears in <paramref name="target"/>. Lines are counted wherever \n appears.         /// </summary>         /// <param name="target"></param>         /// <param name="source"></param>         /// <returns></returns>         public static int GetLineNumberContaining(this string target, string source)         {             if (string.IsNullOrEmpty(target)) return -1;             if (string.IsNullOrEmpty(source)) return -1;             var position = target.IndexOf(source);             if (position == -1) return -1;             var lineCount = 0;             for (var i = 0; i < position; i++)             {                 if (target[i] == '\n') lineCount++;             }             return lineCount;         }     } }