Array Class Collections File String .NET Algorithm ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method Number Regex Sort StringBuilder Struct Switch Time Value Windows

Strings are collections of characters. The C# language introduces the string type. This type allows us to manipulate character data through methods and properties. It provides methods to concatenate, append, replace, search and split. It is used frequently. Text is everywhere on computer systems.
Consider a string of characters. A string is a class that holds characters and provides operations such as subscripting, concatenation, and comparison that we usually associated with the notion of a "string." Stroustrup, p. 328

In this simple program, you can see how a string is created. It is assigned to a string literal "dot". Then another string literal is appended to that string. Finally a method on the string type is called to manipulate the strings again.
LiteralProgram that uses string type [C#]
using System;
class Program
{
static void Main()
{
string value = "dot";
value += "net";
string result = string.Concat(value, "perls");
Console.WriteLine(result);
}
}
Output
dotnetperls
You can split strings in your C# program to isolate and extract substrings with a single function call. Many programs that process text data will need to split strings. We provide examples for Split methods.
Split
Continuing on, the .NET Framework presents several different string searching methods. The most useful one is IndexOf. There are several variants of IndexOf shown here, including Contains.
IndexOf IndexOfAny LastIndexOf LastIndexOfAny ContainsUsually you will not need to copy strings in your C# programs. You can just assign references to existing strings. However, we introduce reasons why you may want to copy strings. We also demonstrate how you can do this.
CopyTo string.CopyIt is often useful to test only the first or last few characters of a string for a certain value. The StartsWith and EndsWith methods provide this ability in the C# language.
StartsWith EndsWithWhen you concat strings, you put them together into a larger string. When you append a string, you put it at the end of another string. We explain concatenating and appending strings in the C# language.
string.Concat
You can also join together many strings in the C# language. Optionally, you can specify a delimiter character, which is inserted between all the original strings into the final string.
string.Join
You can insert a string at any position in an existing string. You can also remove a series of characters starting at any position. To do these tasks please use the Insert or Remove methods.
Insert RemoveYour string data may contain a series of characters that you want to replace with another substring in each place it is found. The Replace method is useful in this case. We show you how to use it.
Replace
In the C# language, you never need to manually count the number of characters in a string. Instead you should access the Length property on a string instance, as the example given here shows.
LengthProgram that uses Length property [C#]
using System;
class Program
{
static void Main()
{
string value = "perls";
Console.WriteLine(value.Length);
Console.WriteLine("cat".Length);
Console.WriteLine(1000.ToString().Length);
}
}
Output
5
3
4
You can acquire a substring of any string by using the Substring method. Also, you can use Substring to truncate or to receive only the right-most part of a string. We demonstrate how you can use this method.
Substring Truncate String String RightThere are a variety of ways to compare two strings for equality in the C# programming language. We reveal aspects of string comparisons—the string.Equals method is most commonly used.
Equals Compare StringComparer StringComparison
Typically, you won't need string constructors in programs, but they can be useful in specific situations. We demonstrate the various overloads of the string constructor in the C# language.
String ConstructorThe concept of interning strings is very old and a classic compiler optimization. It promotes the sharing of common string data resources. We discuss ways that string interning works in the C# language.
string.Intern string.IsInterned
The string type is always used when formatting data types. This includes DateTime data and numeric data. To begin, this program demonstrates the syntax used in some formatting methods. The {0} marker is replaced with the second argument "Net"; the {1} marker is replaced with the third argument "Perls"; and the {2} marker is replaced with the value short.MaxValue. There are many other formatting patterns and adjustments you can make to these substitution markers.
Program that uses format substitutions [C#]
using System;
class Program
{
static void Main()
{
string value = string.Format("Dot {0} {1} = {2}",
"Net",
"Perls",
short.MaxValue);
Console.WriteLine(value);
}
}
Output
Dot Net Perls = 32767
Format examples. We provide examples on using format strings in various methods. The string.Format method, as well as the ToString and DateTime.ToString methods, provides this functionality.
string.Format DateTime Format ToStringParse strings into variables. The .NET Framework provides a large selection of Parse and TryParse methods on various types. These allow you to convert a string representation into a different variable type that represents the same data.
TryParse DateTime.Parse Enum.Parse int.Parse int.TryParse Hex, Converting Hexadecimal NumbersFormat performance. You can improve the performance of formatting operations such as ToString by using a single format string. It is also possible to optimize parsing of integers.
int.Parse Optimization ToString Format Optimization
There are manifold ways to lowercase and uppercase strings in the C# language, transforming "ABC" to "abc" and back again. Some ways are more efficient and lead to faster code than others. Sometimes you don't need to change cases at all. This program simply invokes the ToUpper and ToLower instance methods.
ToUpper ToLowerProgram that uppercases/lowercases [C#]
using System;
class Program
{
static void Main()
{
string value = "perls";
// Convert to uppercase.
value = value.ToUpper();
Console.WriteLine(value);
// Convert to lowercase.
value = value.ToLower();
Console.WriteLine(value);
}
}
Output
PERLS
perlsInvariant methods. The .NET Framework provides invariant case conversion methods. The term invariant refers to how the behavior of the method won't change based on the current culture of the machine.
ToLowerInvariant and ToUpperInvariant Methods
Letters and words. Sometimes you want to only uppercase the first character in a string, or the first character in each word in a string. We provide example code for accomplishing these tasks.
Uppercase First Letter Uppercase Words ToTitleCaseLowercase/uppercase performance. If you are interested in optimizing your program, it is sometimes useful to improve the performance of character case conversions. We show how to use a lookup table for this purpose. And we scan strings to determine if any conversions are necessary in the first place.
String IsUpper and IsLower Methods TextInfo Method Tips ToLower Optimization
Whitespace methods which help us modify space and newline characters in string data. The Trim method is useful. Strings sometimes contain characters at their starts or ends that you do not want. Often, you want to remove leading or trailing whitespace. You can also remove other characters.
Trim TrimEnd TrimStartProgram that uses whitespace Trim method [C#]
using System;
class Program
{
static void Main()
{
string value = " Dot Net Perls ";
Console.Write("*");
Console.Write(value.Trim());
Console.WriteLine("*");
}
}
Output
*Dot Net Perls*Newlines and whitespace. It is common to encounter newline or whitespace characters in strings. The C# language gives us several methods that test for or generate newlines and whitespace characters.
Environment.NewLine string.IsNullOrWhitespace Whitespace Line CountPad strings. Trimming a string removes extra characters on either end. Padding a string instead adds extra characters. We demonstrate how the various padding methods work in the C# programming language.
PadLeft PadRight
Empty strings. How can you handle empty strings in your C# program? We introduce various benchmarks and tests for empty strings. The best way to test empty strings is debated.
Empty String Examples Null String Usage string.Empty string.IsNullOrEmpty
Each string contains data that is made up of individual characters. There are several ways you deal with these chars, typically by using looping constructs.
Change Characters in String String Char Tips String For-Loop
When a string contains a number in its data, you cannot use that number directly. Instead, you need to parse it into another data type. We explore issues related to numeric strings.
String Is Number Increment String NumberStrings in the C# language are stored in Unicode form. You can change the Unicode form to a variety of different normalization forms, as we demonstrate.
Normalize IsNormalized
When a string is passed to another method, its characters are never copied. Instead just the four or eight byte reference to its data is copied. This vastly improves the performance of method calls with string parameters or return values. And strings are immutable, which means you can modify the string in the method and it will not mess up any other parts of your program.
Program that uses string parameter [C#]
using System;
class Program
{
static void Main()
{
string value = "medicine";
int result = GetDoubleLength(value);
Console.WriteLine(value);
Console.WriteLine(result);
}
static int GetDoubleLength(string value)
{
// This method receives a string parameter.
// ... The character data is not copied.
return value.Length * 2;
}
}
Output
medicine
16String parameter notes. Only the four or eight byte reference is passed to the GetDoubleLength method. The actual string literal "medicine" is left alone and only found in one place in memory. And if the method is inlined, no copying will be necessary.

Though in typical usage they are pretty fast, strings are sometimes used in an inefficient way. We help remedy this problem with these examples, which show ways to improve string handling performance.
Split Improvement Split Optimization String Memory String Performance Replace Optimization Replace Performance ToString Integer Optimization
Here, we describe various ways you can use the string type. You can use modifiers on strings and also use strings as parameters and properties.
PHP Explode Function Split Delimiter Use Split Escape Characters String Append: Add Strings Together String Property String ToString StringSplitOptions Enumeration
Immutability—the concept that string data cannot be changed—renders it possible for many methods to share the same string data without any worries about the string entering an invalid state. But this advantage also means strings cannot be appended to without copying them to a new region of memory.