Programming Strings Using C#: Mahesh Chand
Programming Strings Using C#: Mahesh Chand
This free book is provided by courtesy of C# Corner and Mindcracker Network and its
authors. Feel free to share this book with your friends and co-workers. Please do not
reproduce, republish, edit or copy this book.
Mahesh Chand
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Strings in C#
In any programming language, to represent a value, we need a data type. The Char data type
represents a character in .NET. In .NET, the text is stored as a sequential read-only collection of Char
objects. There is no null-terminating character at the end of a C# string; therefore a C# string can
contain any number of embedded null characters ('\0').
The System.String data type is used to represent a string. A string in C# is an object of type
System.String.
The following code creates three strings with a name, number and double values.
// String of characters
System.String authorName = "Mahesh Chand";
// String made of an Integer
System.String age = "33";
// String made of a double
System.String numberString = "33.23";
Here is the complete example that shows how to use stings in C# and .NET.
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
// Define .NET Strings
// String of characters
System.String authorName = "Mahesh Chand";
// String made of an Integer
System.String age = "33";
// String made of a double
System.String numberString = "33.23";
// Write to Console.
Console.WriteLine("Name: {0}", authorName);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Number: {0}", numberString);
Console.ReadKey();
}
}
}
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
String Class
The string class defined in the .NET base class library represents text as a series of Unicode characters. The
string class provides methods and properties to work with strings.
The string class has methods to clone a string, compare strings, concatenate strings, and copy strings. This class
also provides methods to find a substring in a string, find the index of a character or substring, replace
characters, spilt a string, trim a string, and add padding to a string. The string class also provides methods to
convert a string characters to uppercase or lowercase.
Check out these links to learn about a specific operation or functionality of strings.
.NET defines all data types as a class. The System.String class represents a collection of Unicode
characters also known as a text. The System.String class also defines the properties and methods to
work with string data types.
The string class is equivalent to the System.String in C# language. The string class also inherits all the
properties and methods of the System.String class.
Create a string
There are several ways to construct strings in C# and .NET.
The String class has several overloaded constructors that take an array of characters or bytes. The
following code snippet creates a string from an array of characters.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
string name = new string(chars);
Console.WriteLine(name);
You simply define a string type variable and assign a text value to the variable by placing the text
value without double quotes. You can put almost any type of characters within double quotes accept
some special character limitations.
The following code snippet defines a string variable named firstName and then assigns text value
Mahesh to it.
string firstName;
firstName = "Mahesh";
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string numberString = "33.23";
Console.ReadKey();
}
}
}
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Sting concatenation operator (+) can be used to combine more than one string to create a single
string. The following code snippet creates two strings. The first string adds a text Date and current
date value from the DateTime object. The second string adds three strings and some hard coded text
to create a larger string.
Console.WriteLine(nowDateTime);
Console.WriteLine(authorDetails);
Some properties and methods of the String class returns a string object such as SubString method.
The following code snippet takes one sentence string and finds the age within that string. The code
returns 33.
The String.Format method returns a string. The following code snippet creates a new string using the
Format method.
The ToString method returns a string. We can apply ToString on pretty much any data type that can
be converted to a string. The following code snippet converts an int data type to a string.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Get all characters of a string using C#
The following code snippet reads all characters of a string and displays on the console.
Size of string
The Length property of the string class returns the number of characters in a string including white
spaces.
The following code snippet returns the size of a string and displays on the console.
We can use the string.Length property to get the number of characters of a string but it will also
count an empty character. So, to find out exact number of characters in a string, we need to remove
the empty character occurrences from a string.
The following code snippet uses the Replace method to remove empty characters and then displays
the non-empty characters of a string.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
// Size after empty characters are removed
Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length);
ToCharArray method converts a string to an array of Unicode characters. The following code snippet
converts a string to char array and displays them.
Empty String
An empty string is a valid instance of a System.String object that contains zero characters. There are
two ways to create an empty string. We can either use the string.Empty property or we can simply
assign a text value with no text in it.
An empty string is sometimes used to compare the value of other strings. The following code snippet
uses an empty string to compare with the name string.
if (name != empStr)
{
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Console.WriteLine(name);
}
In real world coding, we will probably never create an empty string unless you plan to use it
somewhere else as a non-empty string. We can simply use the string.Empty direct to compare a
string with an empty string.
if (name != string.Empty)
{
Console.WriteLine(name);
}
if (name != empStr)
{
Console.WriteLine(name);
}
if (name != string.Empty)
{
Console.WriteLine(name);
}
Null String
A null string is a string variable that has not been initialized yet and has a null value. If you try to call
any methods or properties of a null string, you will get an exception. A null string valuable is exactly
same as any other variable defined in your code.
A null string is typically used in string concatenation and comparison operations with other strings.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
{
Console.WriteLine(name + " is neither null nor empty");
}
An empty string is a valid instance of a System.String object that contains zero characters. There are
two ways to create an empty string. We can either use the string.Empty property or we can simply
assign a text value with no text in it.
An empty string is sometimes used to compare the value of other strings. The following code snippet
uses an empty string to compare with the name string.
if (name != empStr)
{
Console.WriteLine(name);
}
A null string is a string variable that has not been initialized yet and has a null value. If you try to call
any methods or properties of a null string, you will get an exception. A null string valuable is exactly
same as any other variable defined in your code.
A null string is typically used in string concatenation and comparison operations with other strings.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
{
Console.WriteLine(name + " is neither null nor empty");
}
Immutable String
Strings in .NET are immutable. Once a string is created, it cannot be modified. It may appear to you
that you are reassigning a new value to the same string object but that’s not true. Every time you
assign a new value to an existing string object, a new object is being created and old object is being
released by the CLR. That means you must be careful when dealing with string operations in C# and
.NET. If you are doing lot of string operations, the StringBuilder class is recommended.
The following code snippet defines two string instances and then we change the value of the first
string with the value of the second string. You would think, you are still using same old name variable
but actually the name in the third line is a new object.
Clone a string
The Clone method of string class is used to clone a string. The Clone method returns the reference of
the same string. The following code snippet clones a string.
Console.WriteLine(authorName);
Console.WriteLine(cloneAuthor);
Compare strings
The string class has three compare methods with several overloaded forms – Compare,
CompareOrdinal, and CompareTo.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The Compare method compares two strings and returns an integer value that indicates their relative
position in the sort order. The return value of Compare method can be less than zero, greater than
zero or equals to zero depending on if one string comes before or after in the sort order. The
Compare method has 8 overloaded forms. It is recommended to use the overloaded method with
StringComparison. Check out best practices for using strings in .NET.
The following code compares two strings and return results on the System console.
The CompareOrdinal method compares two strings by evaluating the numeric values of the
corresponding character in each string.
The following code compares two strings using the CompareOrdinal method and return results on
the System console.
The CompareTo method is an instance method. It compares a value (either a string or on object) with
a string instance. Return values of this method are same as the Compare method. The following
source code compares two strings.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The following code compares two strings using the CompareTo method and return results on the
System console.
Copy a string
The string class provides two methods to copy strings – Copy and CopyTo.
The Copy method copies the contents of a string to another. The Copy method is a static method and takes a
string as input and returns another string with the same contents as the input string. For example, the following
code copies authorName string to copyAuthor string.
The CopyTo method copies a specified number of characters from a specified position in this instance to a
specified position in an array of characters. For example, the following example copies contents of str1 to an
array of characters. You can also specify the starting character of a string and the number of characters you
want to copy to the array.
Concatenate strings
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The Concat method of the string class concatenates one or more strings and objects and a
combination of all.
The following code snippet shows different forms of sting and object concatenation.
Ends With
The EndsWith method returns true if a strings ends with a specified string. The following code snippet
checks if a string ends with “C# Corner”.
Starts With
The StartsWith method returns true if a strings starts with a specified string. The following code
snippet checks if a string starts with “Mahesh”.
Format a C# String
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The string.Format method is used to create formatted strings and concatenate multiple strings representing
multiple objects. The Format method automatically converts any passed object into a string.
For example, the following code uses an integer, a floating number and string values and formats them into a
string using the Format method.
int val = 7;
string name = "Mr. John";
float num = 45.06f;
string str = String.Format("Days Left : {0}. Current DataTime: {1:u}. \n String: {2}, Float: {3}", val, DateTime.Now, name,
num);
Console.WriteLine(str);
The Length property of the String class returns the number of characters within a string. The following code
snippet in returns the number of characters in a string.
The Chars property of a string represents all characters in a string. This property is an indexer that means we do
not need to specify the property explicitly.
The following code snippet in loops through all characters of a string and displays on the console.
The IndexOf and LastIndexOf methods can be used to find an index of a character within a string. The IndexOf
method returns the 0 based index of the first occurrence of a character. If a character is found, it returns the
index of the character; otherwise returns -1;
This method has several overloaded forms and hence can be applied on the entire string or a portion of the
string by specifying the start and end positions of characters in the string.
The LastIndexOf method returns the 0 based index of the last occurrence of a character found in a string.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The following code snippet uses various forms of IndexOf and LastIndexOf methods. As you can see from this
code, we can even specify what part of a string you want to search for. The second parameter of IndexOf and
LastIndexOf takes the starting index and third parameter is the number of characters after the starting index.
The IndexOfAny and LastIndexOfAny methods can be used to find an index of any character of an array of
characters within a string. The IndexOfAny method returns the 0 based index of the first occurrence of a
character. If a character is found, it returns the index of the character; otherwise returns -1.
This method has several overloaded forms and hence can be applied on the entire string or a portion of the
string by specifying the start and end positions of characters within a string.
The LastIndexOfAny method returns the 0 based index of the last occurrence of a character found in a string.
The following code snippet uses various forms of IndexOfAny and LastIndexOfAny methods. As you can see
from this code, we can even specify what part of a string you want to search for. The second parameter of
IndexOf and LastIndexOf takes the starting index and third parameter is the number of characters after the
starting index.
Console.WriteLine(authorName.LastIndexOfAny(findChars));
Console.WriteLine(authorName.LastIndexOfAny(findChars, 5));
Console.WriteLine(authorName.LastIndexOfAny(findChars, 5, 5));
Removing String in C#
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The Remove method deletes a specified number of characters from a string at a specified position. This method
returns the result as a string.
th
For example, the following code removes 13 characters from index starting at 16 position.
Replace String in C#
The Replace method replaces all occurrences of a specified character in a string. For example, the following
source code replaces all occurrences of string “author” with string “writer” in the string.
Split String in C#
The Split method separates strings by a specified set of characters and places these strings into an array of
strings. The Split method takes an array of separator strings. For example, if you want to separate a string with a
space, you would pass space as a separator. The separated strings are returned in an array of strings.
The following code snippet splits sentence string based on spaces and stores all separated strings in an array.
Uppercase a string in C#
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The ToUpper method of a string converts a string to uppercase . The following code shows how to create an
uppercase string.
Lowercase a string in C#
The ToLower method of a string converts a string to lowercase . The following code shows how to create an
lowercase string.
Padding C# String
The string class provides PadLeft and PadRight methods to pad a string.
The PadLeft method of the string class is used apply left padding on a string. The following code
snippet uses PadLeft method to pad a string.
The PadRight method of the string class is used apply left padding on a string. The following code
snippet uses PadRight method to pad a string.
Trim C# String
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Trimming a string is removing spaces and/or special characters from a string. A sting can be trimmed
from the left side, the right side and also both sides.
The TrimStart method is used to trim a string from the starting and TrimEnd method is used to trip as
string from the end.
Console.WriteLine("TrimString");
// Trim End
string trimmedLeftString = authorInfo.TrimStart();
Console.WriteLine("Trimmed left string:{0}", trimmedLeftString);
Console.WriteLine("Lengh:{0}", trimmedLeftString.Length);
// Trim Start
string trimmedRightString = authorInfo.TrimEnd();
Console.WriteLine("Trimmed right string:{0}", trimmedRightString);
Console.WriteLine("Lengh:{0}", trimmedRightString.Length);
Trim a string in C#
The Trim method trims a string from both end ends by removing white spaces from the start and the
end of a string.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string authorInfo = " Author "+ firstName + " " + lastName + " is "
+ age.ToString() + " years old. ";
Console.WriteLine("Original string:{0}", authorInfo);
Console.WriteLine("Lengh:{0}", authorInfo.Length);
The TrimStart method trims a string from the begging by removing white spaces from the start of a
string.
The following code snippet shows how to trim a string from the start.
// Trim Start
string trimmedRightString = authorInfo.TrimEnd();
Console.WriteLine("Trimmed right string:{0}", trimmedRightString);
Console.WriteLine("Lengh:{0}", trimmedRightString.Length);
The TrimEnd method trims a string from the end by removing white spaces from the end of a string.
The following code snippet shows how to trim a string from the end.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Console.WriteLine("Lengh:{0}", trimmedString.Length);
// Trim End
string trimmedLeftString = authorInfo.TrimStart();
Console.WriteLine("Trimmed left string:{0}", trimmedLeftString);
Console.WriteLine("Lengh:{0}", trimmedLeftString.Length);
C# Substrings
A substring is a part of a string. The Substring method retrieves a substring from a string starting at a
specified position. The Substring method has two overloaded forms. The first form takes just an integer as the
starting position of the substring and returns rest of the string. The second form takes first integer as the starting
position and second integer as the length of the substring.
The Contains method returns true if a substring is a part a string. The following code snippet checks if
a substring exists in a string.
©2012 C# Corner.
SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.