Useful Collection of C# String Manipulation Snippets

Collection of useful string manipulation snippets I have collected which you can copy and paste into your projects or libraries.

By Tim Trott | C# ASP.Net MVC | February 5, 2010
822 words, estimated reading time 3 minutes.

Replace First or Last Occurrence of a String with C#

Two functions to replace just the first or the last occurrence of a string within a string. String.replace will replace ALL occurrences.

C#
public static string ReplaceFirstOccurrence (string Source, string Find, string Replace)
{
    int Place = Source.IndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
    int Place = Source.LastIndexOf(Find);
    string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
    return result;
}

Get String Between Two Others with C#

This useful code snippet will parse a string and get a string between two specified tokens. In the example, I use XML but can be any.

C#
public static string GetStringBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
    string[] result = {string.Empty, string.Empty};
    int iIndexOfBegin = strSource.IndexOf(strBegin);
    
    if (iIndexOfBegin != -1)
    {
        / include the Begin string if desired 
        if (includeBegin)
            iIndexOfBegin -= strBegin.Length;

        strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
        
        int iEnd = strSource.IndexOf(strEnd);
        if (iEnd != -1)
        {
            / include the End string if desired 
            if (includeEnd)
                iEnd += strEnd.Length;
            result[0] = strSource.Substring(0, iEnd);
            / advance beyond this segment 
            if (iEnd + strEnd.Length < strSource.Length)
                result[1] = strSource.Substring(iEnd + strEnd.Length);
        }
    }
    else
        / stay where we are 
        result[1] = strSource;
    return result[0];
}

Original author unknown.

Example Usage to Get String Between Two Others

C#
string Example = "<startTag>Demo Text</startTag>";
string InBetween = GetStringBetween("<startTag>", "</startTag>", Example, false, false)
Console.WriteLine(InBetween); / Outputs Demo Text

You can optionally include the start and end tags with the last two parameters.

How to Generate MD5 Hash of String in C#

This short snippet will generate MD5 hash of a given string value in C# which was useful for passwords but is now considered insecure. Simply pass in a string and the function will return a MD5 hash of the contents.

The MD5 message-digest algorithm is a cryptographically broken but still widely used hash function producing a 128-bit hash value. Although MD5 was initially designed to be used as a cryptographic hash function, it has been found to suffer from extensive vulnerabilities

C#
public string CalculateMD5Hash(string input) 
{ 
  / Calculate MD5 hash from input 
  var md5 = MD5.Create(); 
  byte[] inputBytes = Encoding.ASCII.GetBytes(input); 
  byte[] hash = md5.ComputeHash(inputBytes); 

  / Convert byte array to hex string 
  var sb = new StringBuilder(); 
  for (int i = 0; i < hash.Length; i++) 
  { 
    sb.Append(hash[i].ToString("X2")); 
  } 

  return sb.ToString(); 
}

Generate a Random Strings of Characters with C#

Generate random strings of a given length containing either upper case or lower case letters with this short function snippet. This copy-and-paste function allows you to quickly generate random strings with C# and can be used for random identifiers, codes, semi-secure passwords and anywhere else where you may require a random string to be used.

The chosen strings are not completely random because a mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. To generate a cryptographically secure random number, such as the one that's suitable for creating a random password, use the RNGCryptoServiceProvider class.

Random Strings Function

C#
// <summary>
// Generates random strings with a given length
// </summary>
// <param name="size">Size of the string</param>
// <param name="lowerCase">If true, generate lowercase string</param>
// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
  StringBuilder builder = new StringBuilder();
  Random random = new Random();
  char ch;
  for (int i = 1; i < size+1; i++)
  {
    ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
    builder.Append(ch);
  }
  if (lowerCase)
    return builder.ToString().ToLower();
  else
    return builder.ToString();
}

You may also like to try our lorem ipsum generator for random words and paragraphs.

C# Convert String to Byte Array and Byte Array to String

How to convert string to byte array and vice-versa in C#. Handy functions for dealing with COM objects and some .Net Providers like CWBX. Two methods allow ASCIIEncoding conversion between a C# byte array and string, and vice versa, which is useful for dealing with CWBX.

These functions are handy in dealing with COM objects and some .Net Providers (IBM CWBX, EventLog and so on).

String to Byte Array

C#
public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}

Byte Array to String

C#
public static string ByteArrayToStr(byte[] byteArray)
{
  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  return encoding.GetString(byteArray);
}
C# Code
How to Convert String to Byte Array and Byte Array to String in C#
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 7 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. KE

    On Tuesday 22nd of November 2022, Kevin said

    Worked successfully for me, thank you!

  2. TS

    On Saturday 3rd of September 2022, Tomasz Szymacha said

    Perfect, but throws the 'System.ArgumentOutOfRangeException' exception when 'Find' not found. Need to be caught and return Source then.

  3. VI

    On Sunday 10th of April 2016, Vibhu said

    Thanks for the function

  4. KI

    On Sunday 8th of November 2015, king said

    it cannot handle multiple text with the same tags, i made a program in python which is much easier, but struggling to translate to c#(im a c# newbie), please make it complete.. forsake

  5. CH

    On Friday 12th of December 2014, Claudiu Harn said

    IT WORKED!!! Thanks a lot!

  6. JO

    On Friday 18th of July 2014, Jozef said

    C#
    private string RandomString(int size)
    {
      var random = new Random();
      Func generator = _=>(char)(int)Math.Floor('Z'-'A' * random.NextDouble() + 'A');
      return string.Join("", Enumerable.Range(1, size).Select(generator));
    }
  7. SP

    On Tuesday 14th of May 2013, Stephen P. said

    Nicely done!
    I will use this a LOT!