Represents a sequence of characters.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
The String class represents a sequence of characters. In .NET, strings are immutable objects; once a string object is created, its value cannot be changed. Any operation that appears to modify a string actually creates a new string object.
Strings are fundamental data types in programming and are used extensively for text manipulation, data representation, and user interface elements. The String class provides a rich set of methods for working with strings, including operations such as concatenation, searching, replacing, splitting, and formatting.
Strings in .NET are encoded using UTF-16. The String class is a reference type, but it is treated as a value type in many contexts, particularly with regard to its immutability.
The String class implements several interfaces, including ICloneable, IComparable, IConvertible, IEnumerable, and IList<Char>, providing a wide range of functionalities.
StringBuilder class.
The following example demonstrates common operations with the String class:
using System;
public class Example
{
public static void Main()
{
// String declaration and initialization
string greeting = "Hello";
string name = "World";
string message;
// String concatenation
message = String.Concat(greeting, ", ", name, "!");
Console.WriteLine(message); // Output: Hello, World!
// String formatting
message = String.Format("The length of the message is: {0}", message.Length);
Console.WriteLine(message); // Output: The length of the message is: 14
// Checking if a string contains another string
if (greeting.Contains("lo"))
{
Console.WriteLine("Greeting contains 'lo'."); // Output: Greeting contains 'lo'.
}
// Extracting a substring
string sub = name.Substring(1, 3);
Console.WriteLine(sub); // Output: orl
// Converting to uppercase
string upperGreeting = greeting.ToUpper();
Console.WriteLine(upperGreeting); // Output: HELLO
// Splitting a string
string fruits = "Apple,Banana,Orange";
string[] fruitArray = fruits.Split(',');
Console.WriteLine("Fruits:");
foreach (string fruit in fruitArray)
{
Console.WriteLine("- {0}", fruit);
}
// Output:
// Fruits:
// - Apple
// - Banana
// - Orange
// Joining strings
string joinedFruits = String.Join(" | ", fruitArray);
Console.WriteLine(joinedFruits); // Output: Apple | Banana | Orange
// Checking for null or empty
string nullString = null;
string emptyString = "";
Console.WriteLine("Is nullString null or empty? {0}", String.IsNullOrEmpty(nullString)); // Output: True
Console.WriteLine("Is emptyString null or empty? {0}", String.IsNullOrEmpty(emptyString)); // Output: True
Console.WriteLine("Is greeting null or empty? {0}", String.IsNullOrEmpty(greeting)); // Output: False
}
}