How To Get A Substring From A String In C#
Maybe your like
Overview
You can use the Substring() method to get a substring in C#.
The Substring() method takes the index position to start the retrieval of the substring as a parameter. Substring() can also take an optional parameter, which is the length of strings to return.
Syntax
public string Substring(int startIndex) public string Substring(int startIndex, int length)Parameters
-
startIndex: an integer value that represents the index position the substring should start from.
-
length (optional): specifies the end of the substring.
Return value
The method returns a substring of a particular string.
Example
In the example below, we create some strings and use an index value to specify where the retrieval of the substrings should start from to get their substrings.
// create classclass SubStringGetter{ // main method static void Main() { // create strings string str1 = "Edpresso"; string str2 = "Theodore"; string str3 = "Programming"; // get some substrings string a = str1.Substring(2); string b = str2.Substring(5); string c = str3.Substring(3); // print out substrings System.Console.WriteLine(a); System.Console.WriteLine(b); System.Console.WriteLine(c); }}RunIn the code above, we use Substring() in line 13 to get the substring of Edpresso and start it from character p, which is index 2. The same pattern goes for Theodore and Programming.
Now, let’s specify the end of the substring. So far, we haven’t specified the length of the substring. Let’s do this in the example below by specifying the optional length parameter.
// create classclass SubStringGetter{ // main method static void Main() { // create strings string str1 = "Edpresso"; string str2 = "Theodore"; string str3 = "Programming"; // get some substrings string a = str1.Substring(2, 2); string b = str2.Substring(5, 1); string c = str3.Substring(3, 5); // print out substrings System.Console.WriteLine(a); System.Console.WriteLine(b); System.Console.WriteLine(c); }}RunIn the code above, we specify the length of our substrings.
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Tag » What Is Substring In C#
-
Substring In C# - C# Corner
-
C# | Substring() Method - GeeksforGeeks
-
String.Substring Method (System) | Microsoft Learn
-
C# String Substring() (With Examples) - Programiz
-
C# Substring() Method - Tutorialspoint
-
How To Use C# String Substring
-
C# Substring Examples - Dot Net Perls
-
C# Substring 문자열 자르기 - 개발인생
-
C# String SubString() Method - Javatpoint
-
082 - How To Use C# String Substring - YouTube
-
What Is Substring In C# With Example? [60 Answers Found]
-
How To Check If String Contains Specified Substring In C#?
-
Visual C# .net Strings - Substring - Home And Learn Courses
-
JavaScript String Substring() Method - W3Schools