Strings in C#
Overview
- Reference Data Type: Strings are a reference data type in C#.
- Storage: They are used to store sequences of character objects, representing text.
- Class: A string in C# is an object of the
System.Stringclass. - Operations: The
Stringclass provides a wide range of methods to perform various operations on strings.
Declaration & Initialization
-
Using
stringKeyword:-
Declaration:
string name; // String declaration -
Declaration and Initialization:
string name = "Kamal"; // Declaration and initialization at once
-
-
Creating an Object from
System.StringClass:-
Declaration:
String homeTown; // Declaration -
Declaration and Initialization:
String homeTown = "Colombo"; // Declaration and initialization at once
-
Common String Methods
Here are some commonly used methods from the System.String class:
-
Clone()- Description: Returns a reference to this instance of the string.
- Example:
string original = "Hello"; string copy = (string)original.Clone();
-
Compare(String, String)- Description: Compares two string objects.
- Example:
int result = String.Compare("Apple", "Banana"); // result will be less than 0 because "Apple" is less than "Banana"
-
Concat(String, String)- Description: Concatenates two specified strings.
- Example:
string fullName = String.Concat("John", "Doe"); // fullName will be "JohnDoe"
-
ToString()- Description: Returns an instance of the string.
- Example:
int number = 123; string numberString = number.ToString();
-
Trim()- Description: Removes leading and trailing whitespace characters.
- Example:
string text = " Hello "; string trimmedText = text.Trim(); // "Hello"
-
ToUpper()- Description: Converts a string into uppercase.
- Example:
string text = "hello"; string upperText = text.ToUpper(); // "HELLO"
-
IndexOf(char)- Description: Gets the index of the specified character in the string.
- Example:
string text = "Hello"; int index = text.IndexOf('e'); // index will be 1
-
Substring(Int32)- Description: Retrieves a substring from this instance starting at a specified index.
- Example:
string text = "HelloWorld"; string subText = text.Substring(5); // subText will be "World"
-
Join(String, String[])- Description: Concatenates all the elements of a string array, using the specified separator.
- Example:
string[] words = { "Hello", "World" }; string sentence = String.Join(" ", words); // sentence will be "Hello World"