C# String Type

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

String type

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

Literals

In this simple program, you can see how a string is created and 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.

Literal
Program 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

Split

Split strings

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. Fortunately, we provide examples for Split methods.

Split StringSplitOptions

IndexOf

IndexOf illustration

Continuing on, the .NET Framework presents several different string searching methods, the most useful of which is probably IndexOf. There are several variants of IndexOf shown here, including Contains.

IndexOf IndexOfAny LastIndexOf LastIndexOfAny Contains

Copy

Usually, 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, and also demonstrate how you can do this.

CopyTo string.Copy

StartsWith/EndsWith

It 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, as demonstrated here.

StartsWith EndsWith

Concat

When 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. This site covers concatenating and appending strings in the C# language.

string.Concat String Append: Add Strings Together

Join

Join objects together

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 Join String List

Insert/Remove

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 Remove

Replace

Your 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, and we show you how to use it.

Replace

Length

Length property

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.

Length
Program 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

Substring

Substring method example

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 Right

Compare

There 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

Constructor

New keyword (constructor invocation)

Typically, you won't need string constructors in programs, but they can be very useful in specific situations. We demonstrate how you can use the various overloads of the string constructor in the C# language.

String Constructor

Intern

The 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

Format

Format illustration

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
Examples

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 for you.

string.Format DateTime Format ToString

Parse 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 double.Parse short.Parse Hex, Converting Hexadecimal Numbers

Format performance. You can improve the performance of certain 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

Lowercase/uppercase

Lowercase and uppercase words

There are manifold ways to lowercase and uppercase strings in the C# language, transforming "ABC" to "abc" and back again. However, some ways are more efficient and lead to faster code than others, and sometimes you don't need to change cases at all. For a short introduction, this program simply invokes the ToUpper and ToLower instance methods.

ToUpper ToLower
Program 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
perls

Invariant 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 MethodsNote (please read)

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 ToTitleCase

Lowercase/uppercase performance. If you are interesting 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 also how to scan strings to determine if any conversions are necessary in the first place.

String IsUpper and IsLower Methods TextInfo Method Tips ToLower Optimization

Whitespace

This section provides information

As part of the coverage of strings in the C# language, we focus on whitespace methods, which help us modify space and newline characters in string data. The Trim method is very 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 TrimStart
Program 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 can be used to test for or generate newlines and whitespace characters in your program data.

Environment.NewLine string.IsNullOrWhitespace Whitespace Tips Line Count String Methods

Pad strings. While trimming a string removes extra characters on either end, padding a string adds extra characters. We demonstrate how the various padding methods work in the C# programming language.

PadLeft PadRightQuestion and answer

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

Chars

Char type

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, as we demonstrate here.

Change Characters in String String Char Tips String For-Loop

Numeric strings

Steps

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.

Increment String Number String Number, Test Numeric String Values

Normalize

Strings 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

Performance

Performance optimization

Though in typical usage they are pretty fast, strings are sometimes used in a very 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

Misc.

Miscellaneous

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 Parameter String Property String ToString

Summary

The C# programming language

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. This advantage, though, also means strings cannot be appended to without copying them to a new region of memory.

Dot Net Perls