Files
freeCodeCamp/guide/english/csharp/substring/index.md

47 lines
1.1 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
2019-07-11 03:08:28 +02:00
title: Substring
2018-10-12 15:37:13 -04:00
---
2019-07-11 03:08:28 +02:00
# String.Substring Method
2018-10-12 15:37:13 -04:00
2019-07-11 03:08:28 +02:00
A substring is a contiguous sequence of characters within a string. The `String.Substring` method retrieves those characters. In c# string characters are zero-indexed which means that the first character of a string starts at the 0th position.
## Overloads
* Substring(int32)
* Substring(int32, int32)
The first overload retrieves a substring that starts at a specified character position and continues to the end of the string. The second overload retrieves a substring that starts at a specified character position and has a specified length.
2018-10-12 15:37:13 -04:00
## Example
2019-07-11 03:08:28 +02:00
```csharp
2018-10-12 15:37:13 -04:00
string firstSentence = "Apple, I have.";
string secondSentence = "I have a Pen.";
string thirdSentence = "I am having Fun";
2018-10-12 15:37:13 -04:00
2019-07-11 03:08:28 +02:00
string apple1 = firstSentence.Substring(9);
string pen1 = secondSentence.Substring(7);
2018-10-12 15:37:13 -04:00
2019-07-11 03:08:28 +02:00
string apple2 = firstSentence.Substring(0,5);
string pen2 = secondSentence.Substring(9,3);
Console.WriteLine(apple1);
Console.WriteLine(pen1);
Console.WriteLine(apple2);
Console.WriteLine(pen2);
Console.ReadLine();
2018-10-12 15:37:13 -04:00
```
## Output:
2019-07-11 03:08:28 +02:00
2018-10-12 15:37:13 -04:00
```
2019-07-11 03:08:28 +02:00
>have.
>a Pen.
2018-10-12 15:37:13 -04:00
>Apple
>Pen
2019-07-11 03:08:28 +02:00
2018-10-12 15:37:13 -04:00
```