EN
C# / .NET - get first 2 characters from string
0 points
In this article, we would like to show you how to get the first 2 characters from a string in C#.
Quick solution:
xxxxxxxxxx
1
String text = "1234";
2
String firstCharacters = text.Substring(0, 2);
3
4
Console.WriteLine(firstCharacters); // 12
The below example shows how to use Substring()
method to get the first 2
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
public static void Main(string[] args)
12
{
13
Console.WriteLine(getFirstCharacters("1234", 2)); // 12
14
Console.WriteLine(getFirstCharacters("123", 2)); // 12
15
Console.WriteLine(getFirstCharacters("12", 2)); // 12
16
Console.WriteLine(getFirstCharacters("1", 2)); // 1
17
Console.WriteLine(getFirstCharacters("", 2)); //
18
}
19
}
Output:
xxxxxxxxxx
1
12
2
12
3
12
4
1
5