In C#, a string is a sequence of characters, and it is represented using the `string` data type.
Here are some common operations and methods you can perform on strings in C#:
1. Creating a string: You can create a string by enclosing a sequence of characters in double quotes. For example:
“`csharp
string name = “John Doe”;
“`
2. Concatenating strings: You can concatenate two or more strings using the `+` operator or the `string.Concat` method. For example:
“`csharp
string firstName = “John”;
string lastName = “Doe”;
string fullName = firstName + ” ” + lastName;
string fullName = string.Concat(firstName, ” “, lastName);
“`
3. String interpolation: You can use string interpolation to embed expressions directly within a string. This is done by prefixing the string with the `$` character and using curly braces `{}` to enclose expressions. For example:
“`csharp
string firstName = “John”;
string lastName = “Doe”;
string fullName = $”{firstName} {lastName}”;
“`
4. Accessing individual characters: You can access individual characters in a string using indexing, starting from 0. For example:
“`csharp
string name = “John Doe”;
char firstCharacter = name[0]; // ‘J’
char lastCharacter = name[name.Length – 1]; // ‘e’
“`
5. String length: You can get the length of a string using the `Length` property. For example:
“`csharp
string name = “John Doe”;
int length = name.Length; // 8
“`
6. Changing case: You can change the case of a string using the `ToUpper` and `ToLower` methods. For example:
“`csharp
string name = “John Doe”;
string upperName = name.ToUpper(); // “JOHN DOE”
string lowerName = name.ToLower(); // “john doe”
“`
7. Splitting a string: You can split a string into substrings using the `Split` method. For example:
“`csharp
string sentence = “Hello, world!”;
string[] words = sentence.Split(‘,’); // [“Hello”, ” world!”]
“`
8. Joining multiple strings: You can join multiple strings into a single string using the `Join` method. For example:
“`csharp
string[] words = { “Hello”, “world” };
string sentence = string.Join(” “, words); // “Hello world”
“`
9. Comparing strings: You can compare two strings using the `==` operator or the `Equals` method. For example:
“`csharp
string name1 = “John”;
string name2 = “John”;
bool isEqual = name1 == name2; // true
bool isEqual = name1.Equals(name2); // true
“`
These are just a few of the operations you can perform on strings in C#. There are many more methods available in the `string` class that you can explore in the C# documentation.