EN
C# / .NET - get first character from string
0
points
In this article, we would like to show you how to get the first character from a string in C# / .NET.
Quick solution:
string text = "1234";
string firstCharacters = text.Substring(0, 1);
Console.WriteLine(firstCharacters); // 1
Practical example
The below example shows how to use Substring()
method to get the first character 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", 1)); // 1
Console.WriteLine(getFirstCharacters( "123", 1)); // 1
Console.WriteLine(getFirstCharacters( "12", 1)); // 1
Console.WriteLine(getFirstCharacters( "1", 1)); // 1
Console.WriteLine(getFirstCharacters( "", 1)); //
}
}
Output:
1
1
1
1