How do I get the last four characters from a string in C#?

前端 未结 20 1062
陌清茗
陌清茗 2020-11-30 18:13

Suppose I have a string:

\"34234234d124\"

I want to get the last four characters of this string which is \"d124\". I can use <

相关标签:
20条回答
  • 2020-11-30 19:04
    mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;
    
    0 讨论(0)
  • 2020-11-30 19:04

    I threw together some code modified from various sources that will get the results you want, and do a lot more besides. I've allowed for negative int values, int values that exceed the length of the string, and for end index being less than the start index. In that last case, the method returns a reverse-order substring. There are plenty of comments, but let me know if anything is unclear or just crazy. I was playing around with this to see what all I might use it for.

        /// <summary>
        /// Returns characters slices from string between two indexes.
        /// 
        /// If start or end are negative, their indexes will be calculated counting 
        /// back from the end of the source string. 
        /// If the end param is less than the start param, the Slice will return a 
        /// substring in reverse order.
        /// 
        /// <param name="source">String the extension method will operate upon.</param>
        /// <param name="startIndex">Starting index, may be negative.</param>
        /// <param name="endIndex">Ending index, may be negative).</param>
        /// </summary>
        public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
        {
            // If startIndex or endIndex exceeds the length of the string they will be set 
            // to zero if negative, or source.Length if positive.
            if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
            if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;
    
            // Negative values count back from the end of the source string.
            if (startIndex < 0) startIndex = source.Length + startIndex;
            if (endIndex < 0) endIndex = source.Length + endIndex;         
    
            // Calculate length of characters to slice from string.
            int length = Math.Abs(endIndex - startIndex);
            // If the endIndex is less than the startIndex, return a reversed substring.
            if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();
    
            return source.Substring(startIndex, length);
        }
    
        /// <summary>
        /// Reverses character order in a string.
        /// </summary>
        /// <param name="source"></param>
        /// <returns>string</returns>
        public static string Reverse(this string source)
        {
            char[] charArray = source.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    
        /// <summary>
        /// Verifies that the index is within the range of the string source.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <returns>bool</returns>
        public static bool ExceedsLength(this string source, int index)
        {
            return Math.Abs(index) > source.Length ? true : false;
        }
    

    So if you have a string like "This is an extension method", here are some examples and results to expect.

    var s = "This is an extension method";
    // If you want to slice off end characters, just supply a negative startIndex value
    // but no endIndex value (or an endIndex value >= to the source string length).
    Console.WriteLine(s.Slice(-5));
    // Returns "ethod".
    Console.WriteLine(s.Slice(-5, 10));
    // Results in a startIndex of 22 (counting 5 back from the end).
    // Since that is greater than the endIndex of 10, the result is reversed.
    // Returns "m noisnetxe"
    Console.WriteLine(s.Slice(2, 15));
    // Returns "is is an exte"
    

    Hopefully this version is helpful to someone. It operates just like normal if you don't use any negative numbers, and provides defaults for out of range params.

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