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

前端 未结 20 1061
陌清茗
陌清茗 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 18:51

    assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.

    Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"

    In the above, I need to extract the "273" that I will use in database query

            //find the length of the string            
            int streamLen=StreamSelected.Length;
    
            //now remove all characters except the last 10 characters
            string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));   
    
            //extract the 3 characters using substring starting from index 0
            //show Result is a TextBox (txtStreamSubs) with 
            txtStreamSubs.Text = streamLessTen.Substring(0, 3);
    
    0 讨论(0)
  • 2020-11-30 18:54

    All you have to do is..

    String result = mystring.Substring(mystring.Length - 4);
    
    0 讨论(0)
  • mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?
    

    If you're positive the length of your string is at least 4, then it's even shorter:

    mystring.Substring(mystring.Length - 4);
    
    0 讨论(0)
  • 2020-11-30 18:57

    Ok, so I see this is an old post, but why are we rewriting code that is already provided in the framework?

    I would suggest that you add a reference to the framework DLL "Microsoft.VisualBasic"

    using Microsoft.VisualBasic;
    //...
    
    string value = Strings.Right("34234234d124", 4);
    
    0 讨论(0)
  • 2020-11-30 18:57

    Here is another alternative that shouldn't perform too badly (because of deferred execution):

    new string(mystring.Reverse().Take(4).Reverse().ToArray());

    Although an extension method for the purpose mystring.Last(4) is clearly the cleanest solution, albeit a bit more work.

    0 讨论(0)
  • 2020-11-30 18:59
    string var = "12345678";
    
    if (var.Length >= 4)
    {
        var = var.substring(var.Length - 4, 4)
    }
    
    // result = "5678"
    
    0 讨论(0)
提交回复
热议问题