String data type in C#
In C#, the string data type represents a sequence of characters and is used to store and manipulate text or multiple characters. The string type is a reference type and is declared using the keyword string. string values are enclosed in double quotes (").
Here's an example that demonstrates the usage of the string data type:
string greeting = "Hello, World!";
string name = "John Doe";
Console.WriteLine(greeting); // Output: Hello, World!
Console.WriteLine(name); // Output: John Doe
In the example above, we declare two variables greeting and name of type string and assign them string values. The string data type can store any sequence of characters, including letters, digits, symbols, and spaces.
You can perform various operations on string values, such as concatenation, length retrieval, and accessing individual characters. Here's an example that demonstrates some common operations:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
int fullNameLength = fullName.Length;
char firstCharacter = firstName[0];
Console.WriteLine(fullName); // Output: John Doe
Console.WriteLine(fullNameLength); // Output: 8
Console.WriteLine(firstCharacter); // Output: J
In this example, we declare firstName and lastName as string variables. We then concatenate them with a space in between to create fullName. We retrieve the length of fullName using the Length property and access the first character of firstName using indexing.
The string data type is extensively used in C# for text manipulation, input/output operations, string formatting, and more. It provides a wide range of built-in methods and properties for working with strings efficiently.