Languages
[Edit]
EN

C# / .NET - get first 3 characters from string

0 points
Created by:
Dharman
308

In this article, we would like to show you how to get the first 3 characters from a string in C# / .NET.

Quick solution: 

string text = "1234";
string firstCharacters = text.Substring(0, 3);

Console.WriteLine(firstCharacters);  // 123

 

Practical example

The below example shows how to use Substring() method to get the first 3 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", 3) );  // 123
        Console.WriteLine( getFirstCharacters(  "123", 3) );  // 123
        Console.WriteLine( getFirstCharacters(   "12", 3) );  // 12
        Console.WriteLine( getFirstCharacters(    "1", 3) );  // 1
        Console.WriteLine( getFirstCharacters(     "", 3) );  //
    }
}

Output: 

123
123
12
1

C# / .NET - String (popular problems)

C# / .NET - get first 3 characters of string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join