I have read this question to get first char of the string. Is there a way to get the first n number of characters from a string in C#?
Below is an extension method that checks if a string is bigger than what was needed and shortens the string to the defined max amount of chars and appends '...'.
public static class StringExtensions
{
public static string Ellipsis(this string s, int charsToDisplay)
{
if (!string.IsNullOrWhiteSpace(s))
return s.Length <= charsToDisplay ? s : new string(s.Take(charsToDisplay).ToArray()) + "...";
return String.Empty;
}
}
In C# 8.0 you can get the first five characters of a string like so
string str = data[0..5];
Here is some more information about Indices And Ranges
Try below code
string Name = "Abhishek";
string firstfour = Name.Substring(0, 4);
Response.Write(firstfour);
I don't know why anybody mentioned this. But it's the shortest and simplest way to achieve this.
string str = yourString.Remove(n);
n
- number of characters that you need
Example
var zz = "7814148471";
Console.WriteLine(zz.Remove(5));
//result - 78141
Or you could use String.ToCharArray().
It takes int startindex
and and int length
as parameters and returns a char[]
new string(stringValue.ToCharArray(0,5))
You would still need to make sure the string has the proper length, otherwise it will throw a ArgumentOutOfRangeException
Please try:
yourString.Substring(0, 5);
Check C# Substring, String.Substring Method