EN
C# / .NET - get first 3 characters from string
0 points
In this article, we would like to show you how to get the first 3 characters from a string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "1234";
2
string firstCharacters = text.Substring(0, 3);
3
4
Console.WriteLine(firstCharacters); // 123
The below example shows how to use Substring()
method to get the first 3
characters from the text
string.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static string getFirstCharacters(string text, int charactersCount)
6
{
7
int offset = Math.Min(charactersCount, text.Length);
8
return text.Substring(0, offset);
9
}
10
11
12
public static void Main(string[] args)
13
{
14
Console.WriteLine( getFirstCharacters( "1234", 3) ); // 123
15
Console.WriteLine( getFirstCharacters( "123", 3) ); // 123
16
Console.WriteLine( getFirstCharacters( "12", 3) ); // 12
17
Console.WriteLine( getFirstCharacters( "1", 3) ); // 1
18
Console.WriteLine( getFirstCharacters( "", 3) ); //
19
}
20
}
Output:
xxxxxxxxxx
1
123
2
123
3
12
4
1
5