C# Strings (original) (raw)
Last Updated : 04 Mar, 2025
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# `
// 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# `
// 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 arraychar[] chars = { 'G', 'E', 'E', 'K', 'S' };string str = new string(chars); |
**Create a string using a property or a method | // start and end are the index for str indexstring substr = str.Substring(start, end); |
**Create a string using formatting | string str = string.Format("{0} {1} Cars color " + "are {2}", no.ToString(), cname, clr); |
**Example:
C# `
// 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
C# `
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
C# `
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 |
---|---|---|---|
IndexOf | Finds the index of the first occurrence of a specified character or substring. | Integer | text.IndexOf("World"); |
StartsWith | Checks if a string starts with a specified substring. | Boolean | text.StartsWith("Hello"); |
EndsWith | Checks if a string ends with a specified substring. | Boolean | text.EndsWith("World!"); |
ToUpper | Converts a string to uppercase. | String | text.ToUpper(); |
ToLower | Converts a string to lowercase. | String | text.ToLower(); |
Split | Splits a string into an array based on a specified delimiter. | String Array | fruits.Split(','); |
Join | Combines an array of strings into a single string with a specified delimiter. | String | string.Join(" - ", fruitArray); |
Contains | Checks if a string contains a specified substring. | Boolean | text.Contains("World"); |
PadLeft | Pads a string with spaces or a specified character to a certain length. | String | text.PadLeft(20, '*'); |
PadRight | Pads a string on the right with spaces or a specified character to a certain length. | String | text.PadRight(20, '*'); |
Remove | Removes characters from a string starting at a specified index. | String | text.Remove(5, 7); |
Insert | Inserts a string at a specified index. | String | text.Insert(5, " Beautiful"); |
Trim | Removes leading and trailing whitespaces. | String | text.Trim(); |
Replace | 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# `
// 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’).