25 Mar 2011

Working with Strings in DataVoila/C#

Tips and Tricks Comments Off

In this post, I have compiled a list of code examples for the most common string operations in C#.

Create a String

// Assign "Hello World" to a new variable
string helloWorld = "Hello World";
// Backslashes (and other special characters) must be escaped
string filePath1 = "C:\\Folder\\File1.txt";
// Instead, you can also use a verbatim string literal that is
// prefixed with @ and does not support escape sequences
string filePath2 = @"C:\Folder\File2.txt";

Concatenate Strings

string hello = "Hello";
string world = "World";
string helloWorld = hello + " " + world;
Console.WriteLine(helloWorld);  // "Hello World"

Check if a String Starts or Ends With a SubString

string sample = "DataVoila rocks!";
if (sample.StartsWith("DataVoila"))
    Console.WriteLine("String starts with substring.");
if (sample.EndsWith("!"))
    Console.WriteLine("String ends with substring.");
if (sample.StartsWith("DATAVOILA", StringComparison.InvariantCultureIgnoreCase))
    Console.WriteLine("String starts with substring, ignoring case.");

Search a String

string sample = "DataVoila rocks!";
string searchString = "rock";
if (sample.Contains(searchString))
    Console.WriteLine("Search string found at index {0}.",
    Console.WriteLine("Search string NOT found.");

Extract a Substring From a String

string sample = "The quick brown fox jumps over the lazy dog";
Console.WriteLine(sample.Substring(0, 3));  // "The"
Console.WriteLine(sample.Substring(35));  // "lazy dog"

Insert a Substring to a String

string sample = "Hello World";
Console.WriteLine(sample.Insert(5, ", Lovely"));  // "Hello, Lovely World"

Remove a Substring From a String

string sample = "Hello, Lovely World";
Console.WriteLine(sample.Remove(5, 8));  // "Hello World"

Replace a Substring in a String

string sample = "Hello, Lovely World";
Console.WriteLine(sample.Replace("Lovely", "Cruel"));  // "Hello, Cruel World"

Split a String

string sample = "One,Two,,Three";
char[] delimiter = { ',' };
string[] parts;
parts = sample.Split(delimiter);  // "One", "Two", "", "Three"
//parts = sample.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);  // "One", "Two", "Three"
//parts = sample.Split(delimiter, 2);  // "One", "Two,,Three"
foreach (string part in parts)

Join Strings

string[] parts = new String[] { "One", "Two", "Three" };
Console.WriteLine(string.Join("|", parts));  // "One|Two|Three"

Convert the Case of a String

string sample = "Hello World";
Console.WriteLine(sample.ToLower());  // "hello world";
Console.WriteLine(sample.ToUpper());  // "HELLO WORLD";

Convert a String to TitleCase

string sample = "hello, lovely world";
System.Globalization.TextInfo textInfo =
Console.WriteLine(textInfo.ToTitleCase(sample));  // Hello, Lovely World

Trim a String

string sample = "  Hello World!  ";
Console.WriteLine(sample.Trim());  // "Hello World!"
Console.WriteLine(sample.TrimStart());  // "Hello World!  "
Console.WriteLine(sample.TrimEnd());  // "  Hello World!"
Console.WriteLine(sample.Trim(new char[] { ' ', '!' }));  // "Hello World"

Pad a String

string sample = "42";
Console.WriteLine(sample.PadLeft(5, '0'));  // "00042"
Console.WriteLine(sample.PadRight(4, '.'));  // "42.."

Convert a String to a Numeric Value

string sample1 = "42";
string sample2 = "3.14159";
// Use culture-independent NumberFormatInfo to ensure that "." is recognized
// as decimal separator regardless of current locale settings
IFormatProvider formatProvider = System.Globalization.NumberFormatInfo.InvariantInfo;
int number1 = Convert.ToInt32(sample1);
double number2 = Convert.ToDouble(sample2, formatProvider);
Console.WriteLine("{0} converts to integer value {1}.", sample1, number1);
Console.WriteLine("{0} converts to double value {1}.", sample2, number2);

Iterate Through a String

string sample = "Hello World";
// Use a "for" loop to iterate through the string
for (int i = 0; i < sample.Length; i++)
// Or make a "foreach" loop through the characters
foreach (char c in sample)

Fill a String With Repeating Characters

string sample = new string('*', 10);
Console.WriteLine(sample);  // "**********"

Reverse a String

string sample = "Hello World";
char[] charArray = sample.ToCharArray();
string reversedSample = new string(charArray);
Console.WriteLine(reversedSample);  // "dlroW olleH"

Append a Newline Character

string sample = "Hello" + Environment.NewLine + "World";

Check If a String is Blank

string sample = "";
if (string.IsNullOrEmpty(sample))
    Console.WriteLine("String is null or empty.");

Check If a String Contains a Numeric Value

string sample = "3.14159";
double number;
bool isNumber = Double.TryParse(sample,
    System.Globalization.NumberFormatInfo.InvariantInfo, out number);   
if (isNumber)
    Console.WriteLine("'{0}' can be converted to {1}.", sample, number);
    Console.WriteLine("'{0}' cannot be converted to a Double value.", sample);

Check If a String Contains Only Alphanumeric Characters

string sample = "Hello123";
bool isAlphaNum =
    !string.IsNullOrEmpty(sample) &&
    (sample.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
if (isAlphaNum)
    Console.WriteLine("String contains only alphanumeric characters.");
    Console.WriteLine("String contains non-alphanumeric characters.");

Use StringBuilder For Fast String Concatenation

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++)
string sample = sb.ToString();
Console.WriteLine("String of length {0} created.", sample.Length);
Comments are closed.