Mega Code Archive

 
Categories / C# / Data Types
 

Finds a given string and enclosing it with tags provided

// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Utils.cs" company="Collaboris Ltd."> //   Copyright (c) Collaboris Ltd. All rights Reserved. // </copyright> // <summary> //   The utils. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Collaboris.DataAccess {     #region Imports     using System;     using System.Web;     #endregion     /// <summary>     /// The utils.     /// </summary>     public class Utils     {         #region [rgn] Methods (2)         /// <summary>         /// Finds a given string and enclosing it with tags provided.         /// </summary>         /// <remarks>         /// the search is Case Insensitive         /// </remarks>         /// <param name="sourceString">         /// The source string.         /// </param>         /// <param name="findString">         /// The find string.         /// </param>         /// <param name="startTag">         /// The start tag.         /// </param>         /// <param name="endTag">         /// The end tag.         /// </param>         /// <returns>         /// The tag string.         /// </returns>         public static string TagString(string sourceString, string findString, string startTag, string endTag)         {             if (sourceString.IndexOf(findString, StringComparison.InvariantCultureIgnoreCase) == -1)             {                 return sourceString;             }             string newString;             // If this is being called from a Web site, lets Decode              if (HttpContext.Current != null)             {                 newString = HttpContext.Current.Server.HtmlDecode(sourceString);             }             else             {                 newString = sourceString;             }             for (int i = 0; i < newString.Length; i++)             {                 int pos = newString.IndexOf(findString, i, StringComparison.InvariantCultureIgnoreCase);                 // if she isnt found return original string                 if (pos == -1)                 {                     return newString;                 }                 int newPos = pos + startTag.Length + findString.Length;                 newString = newString.Insert(pos, startTag);                 newString = newString.Insert(newPos, endTag);                 i = newPos + endTag.Length;             }             return sourceString;         }                 #endregion [rgn]     } }