What is the usage of the string in C#?
In C#, the data type string represents text. It is a reference type used to store and manipulate string data.
Here are some common ways to use strings:
- Declaring and initializing strings:
- string str1 = “Hello, World!”; // initializing string using double quotes
string str2 = new string(‘A’, 5); // initializing string using character and repeat count - String concatenation:
- str3 is a concatenation of str1 and str2 using the + operator.
str4 is a concatenation of str1 and str2 using the Concat method. - Get the length of the string.
- Get the length of the string using the Length property.
- String indexing and slicing:
- Access the first character of the string using an index.
Extract a substring from the string using the Substring method. - String comparison:
- bool isEqual = str1.Equals(str2); // Utilize the Equals method to compare if the strings are the same
bool isContain = str1.Contains(“Hello”); // Utilize the Contains method to determine if the string contains the specified substring - String formatting:
- Using the Format method, create a formatted string that says “My name is John and I am 25 years old.”
- Replacing and splitting strings:
- Use the Replace method to replace the specified substring in the string.
Use the Split method to split the string into an array of strings. - String conversion:
- Convert the string to an integer using the Parse method, Convert the string to a float using the Parse method, Convert the number to a string using the ToString method.
These are just some examples of how to use strings, there are many other methods and properties available for manipulating strings.