Useful Collection of C# String Manipulation SnippetsCollection of useful string manipulation snippets I have collected which you can copy and paste into your projects or libraries.
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.
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.
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
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
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
// <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
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
Byte Array to String
public static string ByteArrayToStr(byte[] byteArray)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetString(byteArray);
}