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:
String text = "1234";
String firstCharacters = text.Substring(0, 2);
Console.WriteLine(firstCharacters); // 12
Practical example
The below example shows how to use Substring()
method to get the first 2
characters from the text
string.
using System;
public class StringUtils
{
public static String getFirstCharacters(String text, int charactersCount)
{
int offset = Math.Min(charactersCount, text.Length);
return text.Substring(0, offset);
}
public static void Main(string[] args)
{
Console.WriteLine(getFirstCharacters("1234", 2)); // 12
Console.WriteLine(getFirstCharacters("123", 2)); // 12
Console.WriteLine(getFirstCharacters("12", 2)); // 12
Console.WriteLine(getFirstCharacters("1", 2)); // 1
Console.WriteLine(getFirstCharacters("", 2)); //
}
}
Output:
12
12
12
1