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);
}
}
OutputName: 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 array char[] 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 index string 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);
}
}
OutputMethod 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);
}
}
OutputGeeksforGeeks 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);
}
}
OutputElement 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]);
}
}
}
Outputvalue 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’).
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers