C# Strings
In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is an important concept, and sometimes people get confused about whether the string is a keyword, an object, or a class. So, let’s clear out this concept.
A string is represented by the class System.String. The “string” keyword is an alias for System.String class, and instead of writing System.String one can use String, which is a shorthand for System.String class. So we can say that both string and String can be used as an alias of System.String class. So string is an object of System.String class.
Example:
// creating the string using string keyword
string s1 = “GeeksforGeeks”;// creating the string using String class
String s2 = “GFG”;// creating the string using String class
System.String s3 = “Pro Geek”;
The String class is defined in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects, which represent a string. The maximum size of String object in memory is 2GB or about 1 billion characters. System.String class is immutable, i.e, once created, its state cannot be altered.
// C# program to declare string using
// string, String and System.String
// and initialization of string
using System;
class Geeks
{
// Main Method
static void Main(string[] args)
{
// declare a string Name using
// "System.String" class
System.String Name;
// initialization of String
Name = "Geek";
// declare a string id using
// using an alias(shorthand)
// "String" of System.String
// class
String id;
// initialization of String
id = "33";
// declare a string mrk using
// string keyword
string mrk;
// initialization of String
mrk = "97";
// Declaration and initialization of
// the string in a single line
string rank = "1";
// Displaying Result
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Id: {0}", id);
Console.WriteLine("Marks: {0}", mrk);
Console.WriteLine("Rank: {0}", rank);
}
}
Output
Name: Geek Id: 33 Marks: 97 Rank: 1
Key Characteristics of Strings
- Immutable: Once created, the content of a string cannot be altered. Any modification results in the creation of a new string.
- Reference Type: Strings are reference types, but they behave like value types in some scenarios, such as comparison.
- Unicode Support: Strings can contain any Unicode character, allowing support for multiple languages.
- Null and Embedded Nulls: Strings can be null and may also contain embedded null characters (
\0
). - Operator Overloading: Strings support operator overloading, such as
+
for concatenation and==
for comparison.
String Class Properties: The String class has two properties as follows:
- Chars: It is used to get the Char object at a specified position in the current String object.
- Length: It is used to get the number of characters in the current String object. To know more about the string class properties please go to String Properties in C#.
Reading String from User-Input
A string can be read out from the user input. ReadLine() method of console class is used to read a string from user input.
Example:
// C# program to demonstrate Reading
// String from User-Input
using System;
class Geeks
{
// Main Method
static void Main(string[] args)
{
Console.WriteLine("Enter the String");
// Declaring a string object read_user
// and taking the user input using
// ReadLine() method
String read_user = Console.ReadLine();
// Displaying the user input
Console.WriteLine("User Entered: " + read_user);
}
}
Input:
Hello Geeks !
Output:
User Entered: Hello Geeks !
Different Ways to Create Strings
Method | Syntax / Example |
---|---|
Create a string from a literal | string str = “GeeksforGeeks”; |
Create a string using concatenation | string str = str1 + “data”; |
Create a string using a constructor | // Create a string from a character array |
Create a string using a property or a method | // start and end are the index for str index |
Create a string using formatting | string str = string.Format(“{0} {1} Cars color ” + “are {2}”, no.ToString(), cname, clr); |
Example:
// Different Methods for Creating
// String in C#
using System;
public class GFG
{
// Main Method
static public void Main ()
{
// Creating String using string literal
String str = "Geeks";
Console.WriteLine("Method 1: " + str);
// Creating String using concatenation
String str2 = str + "ofGeeks";
Console.WriteLine("Method 2: " + str2);
// Creating a string using a constructor
char[] chars = { 'G', 'E', 'E', 'K', 'S' };
string str3 = new string(chars);
Console.WriteLine("Method 3: " + str3);
// Creating a string using a property or a method
String s = "Geeks For Geeks";
// Index of
int start = s.IndexOf(" ") + 1;
int end = s.IndexOf(" ", start) - start;
string str4 = s.Substring(start, end);
Console.WriteLine("Method 4: " + str4);
// Creating a string using formatting
int i=1;
int j=2;
int sum= i + j;
String str5 = string.Format("Addition of {0} with {1} is {2}"
, i , j , sum );
Console.WriteLine("Method 5: " + str5);
}
}
Output
Method 1: Geeks Method 2: GeeksofGeeks Method 3: GEEKS Method 4: For Method 5: Addition of 1 with 2 is 3
C# String Operations
There are multiple String Operations which we can perform in String in C#. Let us demonstrate the operations using the example as mentioned below:
Example 1: For performing string operation of interpolation
using System;
public class GFG
{
// Main Method
static public void Main ()
{
string name = "GeeksforGeeks";
// Interpolation is performed
string res = $"{name} is the Organisation Name.";
// Printing the String
Console.WriteLine(res);
Console.WriteLine("Length: " + res.Length);
}
}
Output
GeeksforGeeks is the Organisation Name. Length: 39
Example 2: for performing trim, replace and concatenate operation
using System;
public class GFG
{
static public void Main ()
{
string first = " GeEks ";
string second = " forGeeks ";
// trim the String
first=first.Trim();
second=second.Trim();
// Checking element at index 2 first
Console.WriteLine("Element at index 2: " + first[2]);
// replacing the element in String
first=first.Replace("E","e");
Console.WriteLine(first+second);
}
}
Output
Element at index 2: E GeeksforGeeks
In the above, two example we have explored many methods we are not full aware of so, there is a list of Methods associated with Strings in C# attached below.
Methods of C# String
Method | Description | Return Type | Example |
---|---|---|---|
Finds the index of the first occurrence of a specified character or substring. | Integer | text.IndexOf(“World”); | |
Checks if a string starts with a specified substring. | Boolean | text.StartsWith(“Hello”); | |
Checks if a string ends with a specified substring. | Boolean | text.EndsWith(“World!”); | |
Converts a string to uppercase. | String | text.ToUpper(); | |
Converts a string to lowercase. | String | text.ToLower(); | |
Splits a string into an array based on a specified delimiter. | String Array | fruits.Split(‘,’); | |
Combines an array of strings into a single string with a specified delimiter. | String | string.Join(” – “, fruitArray); | |
Checks if a string contains a specified substring. | Boolean | text.Contains(“World”); | |
Pads a string with spaces or a specified character to a certain length. | String | text.PadLeft(20, ‘*’); | |
Pads a string on the right with spaces or a specified character to a certain length. | String | text.PadRight(20, ‘*’); | |
Removes characters from a string starting at a specified index. | String | text.Remove(5, 7); | |
Inserts a string at a specified index. | String | text.Insert(5, ” Beautiful”); | |
Removes leading and trailing whitespaces. | String | text.Trim(); | |
Replaces occurrences of a substring with another substring. | String | text.Replace(“fun”, “awesome”); | |
String Arrays
We can also create the array of string and assigns values to it. The string arrays can be created as follows:
String [] array_variable = new String[Length_of_array]
Example:
// C# program for an array of strings
using System;
class Geeks
{
// Main Method
static void Main(string[] args)
{
String[] str_arr = new String[3];
// Initialising the array of strings
str_arr[0] = "Geeks";
str_arr[1] = "For";
str_arr[2] = "Geeks";
// printing String array
for(int i = 0; i < 3; i++) {
Console.WriteLine("value at Index position " + i
+ " is " + str_arr[i]);
}
}
}
Output
value at Index position 0 is Geeks value at Index position 1 is For value at Index position 2 is Geeks
String vs System.String
Aspects | string (Keyword) | System.String (Class) |
---|---|---|
Definition | Alias for System.String . | Fully qualified class name in .NET. |
Performance | No difference in performance. | No difference in performance. |
Usage | Commonly used for declaring variables, fields, and properties. | Used for accessing static methods or fully qualifying types. |
Ease of Use | Provides a shorthand for writing code. | More verbose but functionally identical to string . |
Accessing Methods | Methods are accessed via the System.String class. | Static methods like String.Substring , String.IndexOf , etc., are accessed directly. |
Keyword or Class | C# keyword. | .NET class. |
Note: In .NET, the text is stored as a sequential collection of the Char objects so there is no null-terminating character at the end of a C# string. Therefore a C# string can contain any number of embedded null characters (‘\0’).