The .NET string class is quite comprehensive, yet some common string functions are missing or not entirely obvious. This article provides quick tips on using .NET strings.
Fill a String with Repeating Characters
To fill a string with repeating characters, use the string class constructor. For example, to fill a string with twenty asterisks:
string s = new string( '*', 20 );
Check for Blank String
A blank string can be represented by a null reference or empty string (String.Empty or “”). If you attempt to call a method on a null string, an exception will occur. Hence, to check for a blank string, you should use the new .NET v2.0 static function String.IsNullOrEmpty:
String.IsNullOrEmpty( s )
String.Empty vs. “”? It Doesn’t Matter
There has been endless debate on the Web whether it’s better to represent an empty string with String.Empty or blank quotes “”. However, tests show there is minimal performance difference between String.Empty and “” even when creating a billion empty strings.
Reverse a String
There has been extensive analysis on algorithms to reverse a string. The following is a good balance between speed and clarity and works well with Unicode and alternate character sets:
static public string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); }
Compare Strings
Because a string reference can be null, you should avoid using the equality symbol == or the Compare member function when comparing strings. Instead, use the static String.Compare method. This method has the advantage that it can handle null string references, compare strings ignoring case, and compare strings using a specific culture:
if (String.Compare( s1, s2, true ) == 0)
Convert String to Numeric Value
Each numeric data type such as int, Int32, double, etc. has a static TryParse method that converts a string to that data type without throwing an exception. The method returns a bool whether the string contained a value with the specified data type. For example:
string s = "42"; int i; int.TryParse( s, out i );
Use Literal Strings for File Paths
A literal string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters. This makes literal strings ideal for file paths that naturally contain many backslashes. To create a literal string, add the at-sign @ before the string’s opening quote. For example:
string path = @"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe";
String Right
Noticeably absent from the string class is the Right method. But you can replicate it easily using the Substring method. Here is a simple method that wraps this up nicely:
static string Right( string s, int count ) { string newString = String.Empty; if (s != null && count > 0) { int startIndex = s.Length - count; if (startIndex > 0) newString = s.Substring( startIndex, count ); else newString = s; } return newString; }
IndexOf Ignoring Case
The string’s IndexOf methods are all case-sensitive. Fortunately, the Globalization namespace contains the CompareInfo class that includes a case-insensitive IndexOf method. For example:
using System.Globalization;string s1 = "C# is a GREAT programming language."; string s2 = "great"; CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; int i = Compare.IndexOf( s1, s2, CompareOptions.IgnoreCase );
Copyright © 2007-8 Tiwebb Ltd. All rights reserved. This material may not be published, broadcast, rewritten or redistributed without explicit permission from Tiwebb Ltd.


Is there any difference between String.empty and string.empty (The primitive vs the class)? Is either preferable?
String.Empty is identical to string.Empty.
“The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3
http://msdn2.microsoft.com/En-US/library/aa691153.aspx
Good topic for an article!
http://www.devtopics.com/in-c-a-string-is-a-string/
Can you test the Right string with
s = “HelloWorld”;
Consol.WriteLn(Right(s,20));
private string Right(string s, int count)
{
string newString = String.Empty;
if (!string.IsNullOrEmpty(s) && count > 0)
{
int startIndex = s.Length - count;
if (startIndex > 0)
newString = s.Substring(startIndex, count);
else
newString = s;
}
return newString;
}
Khayralla,
Yes, much better, I’ve updated the article. Thank you.
I’m trying to return a string out of a string.
Ballard WA - Zip code 98005 -400X200.
How would I chopped that off so it returns each string individually.
Hades, Use the String.Split() method.
http://msdn2.microsoft.com/en-us/library/system.string.split.aspx
Hi it’s me again.
I’m trying to return a token start counting from right to left. Is there any way to indicate:
return token 3
starting count from right,
the string is “Charlie brown, 12345, USA”
The reason I want to do from token USA to the left is because the tokens on the left are not consistent.
Some times is Charlie Brown and Linus and so on
“Charlie Brown, Linus, Snoopy, 12345, USA”
Please advice..
Hades, here’s a quick console program to demonstrate:
using System;
namespace TokenRight
{
class Program
{
static void Main( string[] args )
{
string s = “Charlie brown, 12345, USA”;
char[] delimiters = new char[] { ‘ ‘, ‘,’ };
string[] words = s.Split( delimiters, StringSplitOptions.RemoveEmptyEntries );
int index = words.Length - 3;
string thirdWordFromRight = index >= 0 ? words[index] : null;
Console.WriteLine( thirdWordFromRight );
Console.ReadLine();
}
}
}
The example for a literal string is wrong.
You’ll end up with a string for a file path containing two backslash characters for every path seperator.
The corrected version:
string path = @”C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe”;
Corrie, good catch, fixed!
He guys,
I was asked the following and ever since I’ve been trying to do it unsuccessfully.
string mystring = “random”;
foreach letter move two sites in the alphabet.
then the result would be “r=t, a=b, n=p, d=f, o=q and so on”
Hi Hades,
I would approach your problem like this:
string myString = “random”;
int length = myString.Length;
StringBuilder sb = new StringBuilder( length );
for (int i = 0; i < length; i++)
{
sb.Append( (char)((int)myString[i] + 2));
}
string myStringConverted = sb.ToString();
Hi, i’m stuck trying to count the amount of characters in a textbox, i need to count everything, punctuation and all. Any ideas?
this.TextBox1.Text.Length
Brilliant, lifesaver, cheers.
Question I want to execute a Store proc that uses three variables of type string such as Fname, Lname, Middle Name.
How would I write it so my application executes the Storeproc in my DB taking the Input string I’m typing on my text box. Do I have to generate single quates around my string?
Sp_AddCustomer ’string1′, ’string2′, ’string3′
THis is what I’m trying to do in the button on a web form.
Button1 ()
{
SqlConnection conn = new SqlConnection(”Server=(local);DataBase=Northwind;Integrated Security=SSPI”);
conn.Open();
string name = textBox1.text;
string Lname = textBox2.text;
string Middle = textBox3.text;
rc =CallDBService(”SP_addcustomer”, name, Lname, Middle);
conn.Close();
}
Your code looks right. What’s the problem?
when I execute the webform it says the text.Box1.text to textBox3.text aren’t part of the context
Sounds like a webforms issue, not a string issue.
Hey i’m trying to do a sort and trim the “,” but it’s not happening what do you think is wrong?
{
string input = “1,9,3,4,3,9,1,5,6,78,”;
string array = input;
char[] c = array.ToCharArray();
Array.Sort(c.Trim(new char[] {’,'}));
Console.WriteLine(c);
Console.ReadLine();
}
Also is there a way to sort them so they the greater numbers are in the middle decresing out without using a function. 123498765
Sorry the previous code is incorrect
{
string input = “1,9,3,4,3,9,1,5,6,78,”;
string array = input.Trim(new char[]{’,'});
char[] c = array.ToCharArray();
Array.Sort(c);
Console.WriteLine(c);
Console.ReadLine();
}
Hades, your question seemed like a good subject for an article:
http://www.csharp411.com/parse-and-sort-comma-delimited-numbers/
Hey Timm,
I’m trying to create a consolote so I copy files from one FOlder to another but i keep getting an error message saying that my dest file is a folder(I know is a folder)
here is my code
string files = @”C:\Documents and Settings\a-hameza\Desktop\DataSources\ACA\Test”;
string[] sfiles = Directory.GetFiles(@”C:\Documents and Settings\a-hameza\Desktop\DataSources\ACA\”);
//foreach (string file in files)
// File.Delete(file);
foreach (string sfile in sfiles)
File.Copy(sfile, files);
Hades, I posted a simple solution here:
http://www.csharp411.com/c-copy-folder-recursively/
this page is very usefull for me! thank you!
This was of great help..!
Hi,
I really find this site useful. And I have been able to apply the codes here in my C# applications
J. Mutunga
From Nairobi Kenya
Very useful article.Timm you write ; tests show there is minimal performance difference between String.Empty and “” even when creating a billion empty strings. May i know who win in minimal performance difference ?
Thanks and regards
Dev