How to get the first five character of a String

后端 未结 20 2244
醉酒成梦
醉酒成梦 2020-12-01 05:01

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#?

相关标签:
20条回答
  • 2020-12-01 05:18

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:20

    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

    0 讨论(0)
  • 2020-12-01 05:21

    Try below code

     string Name = "Abhishek";
     string firstfour = Name.Substring(0, 4);
     Response.Write(firstfour);
    
    0 讨论(0)
  • 2020-12-01 05:22

    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
    
    0 讨论(0)
  • 2020-12-01 05:23

    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

    0 讨论(0)
  • 2020-12-01 05:24

    Please try:

    yourString.Substring(0, 5);
    

    Check C# Substring, String.Substring Method

    0 讨论(0)
提交回复
热议问题