String Class

System

Summary

Represents text as a sequence of code points. The String class is a fixed-size value type that represents an ordered sequence of characters. All operations on String return a new String object. This is because String objects are immutable, meaning that once a String object is created, its value cannot be changed.

Description
Members
Example

Overview

The String class is fundamental to text manipulation in .NET. Its immutability guarantees that string data remains unchanged once created, simplifying multithreaded programming and ensuring data integrity. It provides a rich set of methods for searching, comparing, concatenating, and transforming strings.

Key Characteristics

  • Immutable: Once created, a string's value cannot be modified. Any operation that appears to modify a string actually creates a new string object.
  • Sequence of Characters: Internally, a string is represented as an ordered collection of Unicode characters.
  • Value Type Semantics (in some contexts): Although a reference type, strings often behave like value types due to their immutability and optimizations like string interning.
  • Rich API: Offers numerous static and instance methods for common string operations.

Important Note

For scenarios involving frequent modifications to text data, consider using the StringBuilder class, which is mutable and more efficient for such operations.

In this article

Properties

Name Description
Chars.Length Gets the number of characters in the current String object.
IsNormalized() Indicates whether the UTF-16 encoding of the current string is in the normalized (canonical) form.
IsNormalized(NormalizationForm) Indicates whether the UTF-16 encoding of the current string is in the specified normalized form.

Methods

Name Description
CompareTo() Compares the current string instance to another string or object, using the specified comparison rules, and returns an integer that indicates whether the current string precedes, includes, or follows the other object in sort order.
Contains() Returns a value indicating whether a specified substring occurs within this string.
EndsWith() Determines whether the end of this string instance matches the specified string.
Format() Replaces the format item in a specified string or a span of characters to their string representation of a specified object.
IndexOf() Returns the zero-based index of the first occurrence of a specified character or substring within this string.
Join() Concatenates the elements of a collection, using the specified separator between each element.
Replace() Returns a new string in which all occurrences of a specified string in this instance are replaced with another specified string.
Split() Splits the current string into a subarray of strings by separating it into substrings.
StartsWith() Determines whether the beginning of this string instance matches the specified string.
Substring() Retrieves a substring from this instance. The substring retrieves the characters in this instance, from the specified index to the end of the instance.
ToCharArray() Copies the characters in this instance to a Unicode character array.
ToLower() Converts this String to lowercase.
ToString() Returns the current String.
ToUpper() Converts this String to uppercase.
Trim() Removes all occurrences of a specified set of characters from the beginning and end of this string.
TrimStart() Removes all leading occurrences of a specified set of characters from the current String object.
TrimEnd() Removes all trailing occurrences of a specified set of characters from the current String object.

Constructors

Name Description
String(Char) Initializes a new instance of the String class by repeating a specified Unicode character a specified number of times.
String(Char[], Int32, Int32) Initializes a new instance of the String class to the value indicated by a subarray of a Unicode character array.
String(SByte[], Int32, Int32, Encoding) Initializes a new instance of the String class to the value indicated by a subarray of a specified array of bytes, using a specified encoding.

Operators

Operator Description
+ Concatenates two strings.
== Compares two strings for equality.
!= Compares two strings for inequality.
< Compares two strings lexicographically.
<= Compares two strings lexicographically.
> Compares two strings lexicographically.
>= Compares two strings lexicographically.

Basic String Usage


using System;

public class Example
{
    public static void Main(string[] args)
    {
        string greeting = "Hello, ";
        string name = "World";
        string message = greeting + name + "!";

        Console.WriteLine(message); // Output: Hello, World!

        if (message.Contains("World"))
        {
            Console.WriteLine("The message contains 'World'.");
        }

        string upperMessage = message.ToUpper();
        Console.WriteLine(upperMessage); // Output: HELLO, WORLD!

        char[] chars = message.ToCharArray();
        Console.WriteLine("First character: " + chars[0]); // Output: First character: H
    }
}
                        

String Formatting


using System;

public class StringFormatting
{
    public static void Main(string[] args)
    {
        string productName = "Laptop";
        int quantity = 2;
        decimal price = 1200.50m;

        string invoice = string.Format(
            "Product: {0}, Quantity: {1}, Total: {2:C}",
            productName,
            quantity,
            quantity * price
        );

        Console.WriteLine(invoice);
        // Output: Product: Laptop, Quantity: 2, Total: $2,401.00

        // Using interpolated strings (C# 6 and later)
        string interpolatedInvoice =
            $"Product: {productName}, Quantity: {quantity}, Total: {quantity * price:C}";
        Console.WriteLine(interpolatedInvoice);
    }
}