In C# programming, a string is an instance of the System.String class representing a series of characters. Enclosed in double quotes, a string variable stores a character sequence and is declared using the string keyword. Various string operations like merging, comparing, extracting substrings, searching, trimming, replacing, etc., can be carried out. Strings are frequently employed in tasks related to processing text, receiving user input, handling file operations, and formatting data.
The CSS code snippet shown below defines the styling for a placeholder diagram. The background is set as a linear gradient from #374151 to #1f2937, with a border radius of 12px, padding of 40px, and margin of 20px on the top and bottom. The content is centered within the diagram.
.placeholder-diagram {
background: linear-gradient(135deg, #374151 0%, #1f2937 100%);
border-radius: 12px;
padding: 40px;
margin: 20px 0;
text-align: center;
}
.placeholder-diagram .placeholder-icon {
font-size: 3rem;
margin-bottom: 10px;
}
.placeholder-diagram .placeholder-text {
color: #9ca3af;
font-size: 1rem;
}
For instance, when we compose a text on our mobile device, like "Greetings, John", the device stores this information internally as a string. Likewise, an email identifier such as john@gmail.com is also considered a string since it consists of a sequence of characters.
Syntax:
It has the following syntax.
string variableName = "Your text here";
In this particular syntax,
- String: This keyword is utilized to declare the string variable.
- VariableName: The name of the variable defines this.
Declaring and Initializing a String in C#
There are multiple methods to declare and set the initial value for a string variable in C# .
Declaration without initialization
If we intend to define a string utilizing simple and System.String, we can employ the subsequent syntax:
string myString1;
// Declaration using System.String.
System.String myString2;
Initializing with a string literal
To assign a string with a string literal at the initialization stage, we can employ the subsequent syntax:
string myString3 = "Welcome to C# Programming tech";
String Initialization using Local Variables
By utilizing the var keyword, we have the capability to generate a string with implicit typing.
var localString = "Still a strongly-typed string.";
String Initialization using a Constructor
In C#, a string constructor can generate a string from a char, char, or sbyte.
char [] source = {'X', 'Y', 'Z'};
string myString4 = new string (source);
C# Simple String Example
Let's consider an example to demonstrate string manipulation in C#.
Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
string s2 = new string(ch);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
Output:
hello
csharp
Explanation:
In this instance, we explore two methods of string creation in C#. Initially, the string s1 is formed through a string literal, whereas the string s2 is generated from a character array by employing the new string constructor. Ultimately, we display the outcomes of both strings: "hello" and "csharp".
Characteristics of Strings
There are several characteristics of strings in C#. Some of them are as follows.
- Immutable: In the C# programming language, strings are immutable, which means that they can't be modified after creation.
- Reference Type: Strings are a reference type, but they act as a value type in some scenarios.
- Unicode Support: Strings have Unicode characters, which allows support for multiple languages.
- Null and Embedded Null: Strings can be null, which means that it doesn't represent any value, or they can contain an embedded null character (\0).
- Operator Overloading: Strings support the operator overloading, such as (+) for concatenation and (==) for comparison.
C# String Class
In the C# programming language, the String class is an intrinsic class that signifies a sequence of characters. It is contained within the System.namespace and functions as a reference type. This class offers a range of attributes and functions for effectively generating, modifying, and comparing strings.
C# String Methods
The table below illustrates various kinds of functions in the C# programming language.
| Method Name | Description |
|---|---|
| Clone() | It is used to return a reference to the instance of String. |
| Compare(String, String) | It is used to compare two specified String objects. It returns an integer that indicates their relative position in the sort order. |
| CompareOrdinal(String, String) | It is used to compare two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.. |
| CompareTo(String) | It is used to compare the instance with a specified String object. It indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string. |
| Concat(String, String) | It is used to concatenate two specified instances of String. |
| Contains(String) | It is used to return a value, which indicates whether a specified substring occurs within this string. |
| Copy(String) | It is used to create a new instance of String with the same value as a specified String. |
| CopyTo(Int32, Char[], Int32, Int32) | It is used to copy a specified number of characters from a specified position in the instance to a specified position in an array of Unicode characters. |
| EndsWith(String) | It is used to check that the end of the string instance matches the specified string. |
| Equals(String, String) | It is used to determine that two specified String objects have the same value. |
| Format(String, Object) | It is used to replace one or more format items in a specified string with the string representation of a specified object. |
| GetEnumerator() | It is used to retrieve an object that can iterate through the individual characters in this string. |
| GetHashCode() | It returns the hash code for the string. |
| GetType() | It is used to get the Type of the current instance. |
| GetTypeCode() | It is used to return the TypeCode for the class String. |
| IndexOf(String) | It is used to report the zero-based index of the first occurrence of the specified string in the instance. |
| Insert(Int32, String) | It is used to return a new string in which a specified string is inserted at a specified index position. |
| Intern(String) | It is used to retrieve the system's reference to the specified String. |
| IsInterned(String) | It is used to retrieve a reference to a specified String. |
| IsNormalized() | It is used to indicate that the string is in Unicode normalization form C. |
| IsNullOrEmpty(String) | It is used to indicate that the specified string isnullor an Empty string. |
| IsNullOrWhiteSpace(String) | It is used to indicate whether a specified string isnull, empty, or consists only of white-space characters. |
| Join(String, String[]) | It is used to concatenate all the elements of a string array, using the specified separator between each element. |
| LastIndexOf(Char) | It is used to report the zero-based index position of the last occurrence of a specified character within a String. |
| LastIndexOfAny(Char[]) | It is commonly utilized to return the zero-based index of the last occurrence of any character from the specified character array within the string. If none of the characters are found, it returns -1. |
| Normalize() | It is commonly utilized to return a new string with the same textual content, but its binary representation is normalized according to a specified Unicode normalization form. |
| PadLeft(Int32) | It is used to return a new string that right-aligns the characters of the original string by padding them with spaces on the left. |
| PadRight(Int32) | It is used to return a new string that left-aligns the characters of the original string by padding them with spaces on the right. |
| Remove(Int32) | It is used to return a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted. |
| Replace(String, String) | It is used to return a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. |
| Split(Char[]) | It is used to split a string into substrings based on the characters in an array. |
| StartsWith(String) | It is used to check whether the beginning of the current string matches the specified string. |
| Substring(Int32) | It is used to retrieve a substring from the current string instance. The substring starts at a specified character position and continues to the end of the string. |
| ToCharArray() | It is used to copy the characters of the current string to a Unicode character array. |
| ToLower() | It is used to convert a String into lowercase. |
| ToLowerInvariant() | It is used to convert a String into lowercase using the casing rules of the invariant culture. |
| ToString() | It is used to return an instance of String. |
| ToUpper() | It is used to convert a String into uppercase. |
| Trim() | It is used to remove all leading and trailing white-space characters from the current String object. |
| TrimEnd(Char[]) | It is used to remove all trailing occurrences of a set of characters specified in an array from the current String object. |
| TrimStart(Char[]) | It is used to remove all leading occurrences of a set of characters, which is specified in an array, from the current String object. |
C# String Method Example
Let's consider an example to demonstrate the string method in the C# programming syntax.
Example
using System;
class C# Tutorial {
public static void Main() {
// Creating strings
string city = "Delhi";
string country = "India";
// Using ToUpper and ToLower methods
Console.WriteLine("Uppercase: " + city.ToUpper());
Console.WriteLine("Lowercase: " + city.ToLower());
// Using the Trim method
string sp = "Welcome to C# Programming tech";
Console.WriteLine("Trimmed: " + sp.Trim() );
// Using the Replace method
string rep = country.Replace("India", "Bharat");
Console.WriteLine("Replaced String: " + rep);
// Using the Split method
string fruits ="Apple,Banana,Cherry";
string [] fruitArray = fruits.Split(',');
Console.WriteLine("Fruits after split: ");
foreach (string f in fruitArray) {
Console.WriteLine(f);
}
// Using StartsWith and EndsWith methods
Console.WriteLine("Does the city start with 'Del'?" + city.StartsWith("Del"));
Console.WriteLine("Does the country end with 'dia'?" + country.EndsWith("dia"));
// Using the IndexOf method
int index = fruits.IndexOf("Banana");
Console.WriteLine("Index of Banana: " + index);
// Using String Copy method
string copyCity = String.Copy(city);
Console.WriteLine("Copied String: " + copyCity);
// Using Null or Empty Check method
string emptyStr = "";
Console.WriteLine("Is emptyStr null or empty?" + String.IsNullOrEmpty(emptyStr));
}
}
Output:
Uppercase: DELHI
Lowercase: delhi
Trimmed: Welcome to C# Programming tech
Replaced String: Bharat
Fruits after split:
Apple
Banana
Cherry
Does the city start with 'Del'?True
Does the country end with 'dia'?True
Index of Banana: 6
Copied String: Delhi
Is emptyStr null or empty?True
Explanation:
In this instance, we showcase the application of different string techniques in C#. Initially, we apply the conversion functions like ToUpper and ToLower. The trim function eliminates surplus spaces, and the Replace function substitutes a segment of a string. Subsequently, the split function disintegrates the string into an array.
Afterward, the StartsWith function examines beginnings and the EndWith function inspects endings. The IndexOf technique locates where a substring appears within a string. String.Copy is employed to duplicate an existing string, while String.IsNullorEmpty is utilized to verify if a string is either null or empty.
String Literals
C# has three different types of string literals. These are as follows:
- Quoted String Literals
- Verbatim Literals
- Raw String Literals
Next, we will explore each of these text constants individually in C#.
1) Quoted String Literals
In C# programming, quoted string literals are enclosed within double quote characters (") and typically appear on a single line. These literals allow for the utilization of escape sequences to represent special characters such as newline (\n), tab (\t), double quote (\") and backslash (\).
string text1 = " Learning C# is fun and interesting. ";
string text2 = " This sentence\r\n has a line break. ";
/* The resulting string:
This sentence
has a line break.
*/
Numerous escape sequences are employed within string literals.
| Escape sequence | Character Name |
|---|---|
| \' | It represents a single quote |
| \" | It indicates a double Quote |
|
It represents a backslash |
0 |
It shows the null |
n |
It defines the new line |
t |
It is a Horizontal tab |
| \uNNNN | It is a UTF -16 Unicode Character |
| \U00NNNNNN | It is a UTF -32 Unicode Character |
2) Verbatim String Literals
In C#, a verbatim string literal is employed to generate multi-line strings. Utilizing verbatim strings enables the inclusion of special characters and line breaks within the string content. To create a verbatim string, simply prefix the string with the @ symbol before the opening double quotes.
For Example:
string str1 = @" spdf
abc ";
string str2 = @" \mypcsharedproject ";
string str3 = @" xyz@gmail.com ";
3) Raw String Literals
In C#, a verbatim string literal preserves whitespaces, line breaks, and special characters, enabling the breaking of embedded lines. It employs triple quotes (""") to denote the string literals. These literals can encompass any characters without the need for escape sequences, maintaining the exact appearance of the string in the code storage or display.
String Concatenation
In C#, the process of combining String values is done through the (+) operator. This operator enables the merging of two strings into a unified format. Alternately, String.Concat or String.Join methods can also be employed for string concatenation.
C# String Concatenation Example
Let's consider a scenario to demonstrate how strings can be combined in C#.
Example
using System;
class TPT {
public static void Main() {
// Declaration of string variables
string fname = "Hello World";
string lname = " Tech";
// using + operator
string fullName = fname + " " + lname;
// Displaying the result
Console.WriteLine("Full Name: " + fullName);
}
}
Output:
Full Name: C# Tutorial
Explanation:
In this instance, we define a class named TPT and specify string variables within it. Following the initialization of these variables, we employ the (+) operator to combine the string values. Finally, the Console.WriteLine method is utilized to display the resulting output.
String Interpolation
In C#, utilizing string interpolation proves to be a powerful method for string concatenation. This approach enables the direct embedding of variables within a string, thereby enhancing code readability.
C# String Interpolation Example
Let's consider an example to demonstrate string interpolation in C#.
Example
using System;
class TPT
{
public static void Main()
{
string fName = "Welcome to";
string lName = "C# Tutorial";
int age = 24;
// Using string interpolation
string msg = $"Hello, {fName}{lName} and I am {age} years old.";
Console.WriteLine(msg);
}
}
Output:
Hello, Welcome to C# Programming tech and I am 24 years old.
Explanation:
In this illustration, we showcase the application of string interpolation in C#. Initially, we declare three variables: fName, lName, and age, to hold segments of a message and an integer. Subsequently, we employ interpolation by adding a $ sign before the string. This feature enables the formation of a clear and brief message within the msg variable.
Finding the length of a string in C#
Let's consider an example to determine the string's size by utilizing the length property in C#.
Example
using System;
class TPT
{
public static void Main()
{
// Declaration of a string
string msg = "Welcome to C# Programming tech";
// using the length property
int l = msg.Length;
Console.WriteLine($"The string is: {msg}");
Console.WriteLine($"The length of the string: {l}");
}
}
Output:
The string is: Welcome to C# Programming tech
The length of the string: 22
Explanation:
In this instance, we define a class called TPT and establish a string variable named msg. Following the initialization of the value, we employ the Length property to determine the string's character count.
Comparing String
In C# coding language, strings can undergo a comparison through methods like String.Compare, Equals, and == operator. The outcome of this comparison is an integer value indicating if a string is less than, equal to, or greater than another string.
C# String Example to Compare Two Strings
Let's consider a scenario to demonstrate the various techniques for comparing two strings in C#.
Example
using System;
public class StringCompareExample
{
public static void Main()
{
string str1 = "Csharp";
string str2 = "Java";
// Using String.Compare()
int result = String.Compare(str1, str2);
// Using Equals()
bool isEqual = str1.Equals(str2);
// Using ==
bool equalOperator = (str1 == str2);
Console.WriteLine("String.Compare() Result: " + result);
Console.WriteLine("Equals() Result: " + isEqual);
Console.WriteLine("== Operator Result: " + equalOperator);
}
}
Output:
String.Compare() Result: -1
Equals() Result: False
== Operator Result: False
Explanation:
In this illustration, we showcase the comparison of strings using various techniques in C#. In this scenario, the function string.Compare yields a result of -1 as "Csharp" precedes "Java" in alphabetical order. The methods Equals and == both yield False outcomes since the strings are not identical.
Conclusion
In summary, a C# string is a series of characters that serves as a representation of textual information. Strings play a crucial role in programming for the storage and manipulation of textual data like words and sentences. They offer various predefined functions that simplify tasks like combining, altering, comparing, removing whitespace, and searching. Utilizing strings is essential for developing well-structured, optimized, and comprehensible software.
C# String FAQs
1) Define a string in C#?
In C#, a string refers to an instance of the System.String class, serving as a collection of characters. Enclosed within double quotes, a string variable contains a series of characters and is declared using the string keyword.
2) How can we compare two strings in C#?
In C#, strings can be compared using the String.Compare, Equals, and == operator. The String.Compare method returns an integer value that represents whether one string is less than, equal to, or greater than another string.
- If the result is 0, both strings are equal.
- If the result is less than 0, the first string is smaller.
- If the result is greater than 0, the first string is larger.
3) Why does a string immutable in C#?
In C#, a string is immutable, indicating that its value cannot be modified after initialization.
4) What is a string concatenation in C#?
In C#, a String is combined using the (+) operator, enabling the merging of two string values into a unified format.
string greet = "Welcome" + " to" + "C# Tutorial";
5) What is string interpolation in C#?
String interpolation stands out as the optimal method for merging strings. This technique enables the direct inclusion of variables within a string, thereby enhancing code readability.
string name = "John";
string message = $"Hello, {name}!";