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 );
Related posts:


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
what are the different predefined array and string classes?
please help me! i need it for my subject in Programming Language..
Hey Timm,
Is there a way to search for a string in a collection of Integers.
I'm trying to create a method where you pass a SQL colum data Type Integer and I would like to select the ones aren't Integers. Sounds Wird but it is happening. I already tried SQL server but i could't find a way of doing it and Im dealing with terrabytes of data that would take quite a bit doing it manually.
This is the way I'm doing it but it throws an error saying (not all code paths return a value)
——————————————-
static void Main(string[] args)
{
string[] myArray =
{"123″,"446″,"447″,"448″,"449″,"450″,"451″,"452″,"453″,"454″,"455″,"456″,"457″,"458″,"459″,"460″,"461″,"462″,"463″,"464″,"465″,"466″,"467″,"468″,
"469″,"470″,"471″,"472″,"473″,"474″,"475″,"476″,"477″,"478″,"479″,"480″,"481″,"sdfsd","sdfsd","sdfsd","sdfsd","sdfsd","sdfsd","sdfsd","sdfsd","sdfsd","sdfsd" };
Console.WriteLine(ValidateNumericValue(myArray));
Console.ReadLine();
}// End Of Main
public static string ValidateNumericValue(string[] sValues)
{
bool sNumeric;
int i;
int j;
for (i = 0; i < sValues.Length; i++)
{
sNumeric = int.TryParse(sValues[i], out j);
if (!sNumeric)
{
return sValues[i];
}
}
}
}
You need to make sure all code paths return a value. I find the easiest way to ensure this is to have the last line a return statement. Hence you would modify your method as:
public static string ValidateNumericValue(string[] sValues)
{
string s = null;
int j;
for (int i = 0; i < sValues.Length; i++)
{
if (!int.TryParse(sValues[i], out j))
{
s = sValues[i];
}
}
return s;
}
I'm not convinced this method will accomplish what you want, but it should now compile correctly.
Hey Timm this isn't compiling I get a unreachable code error in the i++,
Never mind !!!
abou the Method not acomplishing the task this is a prototype I'll post my solution when done thanks,
You are the best and this is the best C# Site!!!!
Great Site.
I been going crazy trying to figure this out. I originally was setting connString to the server name and kept getting double \\'s. Then I figured I use an app.config key… still the same. I'm new to C# so any pointers will be great
App.Config
Code
string connString;
connString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
Ends up as
System.Configuration.ConfigurationManager.AppSettings["ConnectionString"] "server=\\\\PRESARIOLAPTOP\\SQL2K5;database=DvdLibrary;Integrated Security=true;" string
App.Config entry is;
Don't know why is didn't paste above… It's been a long day
One more try..
key="ConnectionString" value="server=\\PRESARIOLAPTOP\SQL2K5;database=DvdLibrary;Integrated Security=true;"
Scratch that. It works find. It just shows in the IDE with the double backslashes. Displaying it in a MessageBox shows it's formatted correctly
Hi Timm I'm trying to find a file within a Directory by doing a search on the three first element of my FileName(3.0.25)I will alway provide the first three Number in the Code; how ever the file in the directory might have and extra digit 3.0.25.0.
This is What I'm Doing :
DirectoryInfo SourcePath = new DirectoryInfo(@"C:\Scirpts");
int NumberMajor, NumberMinor, ThirdIdx;
NumberMajor = 4;
NumberMinor = 0;
ThirdIdx = 196;
string[] files = Directory.GetFiles(SourcePath.ToString(), String.Format("{0}.{1}.{2}*.sqc", NumberMajor, NumberMinor, ThirdIdx));
foreach (string fileName in files)
{
if (File.Exists(fileName))
Console.WriteLine(fileName);
}
Console.ReadLine();
How can I accoplish this by using a REGEX??
A question for you!
How do I do a thing like this:
richtextBox1.AppenText(myString);
My problem si that I have an application where I want to view the content of files. They are sometimes binary, but I still want to view them as text. But then the string that contains the data has a lot of crazy characters in it and when I try to append this in my textbox or richtextbox it "evaluates" the special characters.
How do I get it to display the string myString as it is, with "\" and all, no escaping.
Very grateful for any hint on how to accomplish this!
Jonas, good question, perhaps you can find your answer here:
http://www.csharp411.com/cleanstripremove-binary-characters-from-c-string/
Hey Timm,
What I found out is that the solution that I implemented ended up to be easier to code and understand.
I tried a number of Regex expressions to look for the file in the folder but every time the compiler would complain about the path not being valid.