...

/

The String Class and Its Methods

The String Class and Its Methods

Learn to use the different options of a C# API to perform pattern matching using a regular expression.

What are strings in C#?

A string is a sequence of characters. The text in a file, the data from a network connection, and the search terms typed by a user are all strings.

In addition to its character content, a string contains metadata about its length and encoding type, such as UTF-8, UTF-16LE, ASCII, and Unicode.

Often, it is necessary to extract this metadata and convert the input stream to a particular encoding to deal with text in foreign languages. Unicode makes it possible to store, represent, and manipulate text from any language using a single character set. Meanwhile, UTF-8 allows an ASCII-compatible encoding that is efficient for manipulating byte strings.

While we can perform string manipulation manually, libraries such as .NET’s System.String provide the tools necessary to process strings without depending on low-level memory access primitives: pointers and array indexing.

The string keyword

The string data type in .NET is an immutable class that represents a sequence of System.Char objects. A Unicode code represents each character in the String object.

The string keyword is an alias for System.String. The String class implements the IEnumerable<Char> interface. Meanwhile, the String class provides methods to create, manipulate, and compare strings.

The code snippets below show how to use strings in C#:

// Declaring a string
string text;

// Initializing a string to null
text = null; 

// Creating an Empty string
string message = System.String.Empty; 

// Initializing a string with literal "Hello!"
string greeting = "Hello!"

Operations on strings

Let’s see a simple string matching problem in C#.

Press + to interact
using System;
class HelloWorld
{
static void Main()
{
string wordToFind = "the";
string[] linesOfText = {"The quick brown fox", "jumped over the lazy dog"}; //Get the list of lines
foreach (string line in linesOfText) {
if (line.Contains("the")) {
Console.WriteLine("Word '{0}' found", wordToFind);
} else {
Console.WriteLine("Word '{0}' NOT found", wordToFind);
}
}
}
}

Below are some of the most useful methods and overloaded operators of the ...