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:

  1. Declaring and initializing strings:
  2. string str1 = “Hello, World!”; // initializing string using double quotes
    string str2 = new string(‘A’, 5); // initializing string using character and repeat count
  3. String concatenation:
  4. str3 is a concatenation of str1 and str2 using the + operator.
    str4 is a concatenation of str1 and str2 using the Concat method.
  5. Get the length of the string.
  6. Get the length of the string using the Length property.
  7. String indexing and slicing:
  8. Access the first character of the string using an index.
    Extract a substring from the string using the Substring method.
  9. String comparison:
  10. 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
  11. String formatting:
  12. Using the Format method, create a formatted string that says “My name is John and I am 25 years old.”
  13. Replacing and splitting strings:
  14. 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.
  15. String conversion:
  16. 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.

广告
Closing in 10 seconds
bannerAds