Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy 4 ký tự cuối chuỗi trong C#

Chuỗi: string str = "Football and Tennis";

Dùng Substring với index = Length - 4:

string res = str.Substring(str.Length - 4);

Ví dụ

using System;

public class Demo
{
    public static void Main()
    {
        string str = "Football and Tennis";
        string res = str.Substring(str.Length - 4);
        Console.WriteLine(res);
    }
}

Kết quả

nnis

An toàn hơn:

string GetLast(string s, int n)
{
    if (string.IsNullOrEmpty(s) || n <= 0) return "";
    if (n >= s.Length) return s;
    return s.Substring(s.Length - n);
}

Cách khác: str[^4..] (Range operator C# 8+), new string(str.TakeLast(4).ToArray()) (LINQ).