简体   繁体   中英

How to remove last numbers of string with different lengths C#

NOTE: The lengths of the last 2 is different. So Length-1 doesn't work(right?)

How do I remove the last numbers from example:

ABStreet 10 552896

ACLane 1520 155

So that it outputs:

ABStreet 10

ACLane 1520

It probbably is already asked somewhere, and I though of TrimEnd, but I can't seem to get the correct code.

Using Regex it would look like this:

class Program
{
    static void Main(string[] args)
    {
        string test = "ABStreet 10 552896";

        test = Regex.Replace(test, @"\s\d*$",string.Empty);
        Console.WriteLine(test);
    }
}

Or with TrimEnd:

class Program
{
    static void Main(string[] args)
    {
        string test = "ABStreet 10 552896";

        test = test.TrimEnd('1', '2', '3', '4', '5', '6', '7', '8', '9', '0').Trim();
        Console.WriteLine(test);
    }
}
var x = "ABStreet 10 552896";
var y = "ACLane 1520 155";
Console.WriteLine(x.Substring(0, x.LastIndexOf(' ')));
Console.WriteLine(y.Substring(0, y.LastIndexOf(' ')));

You could use a simple Regex expression

List<string> elements = new List<string>() {"ABStreet 10 552896","ACLane 1520 155"};

Regex r = new Regex(@"\d+$");
foreach(string s in elements)
    Console.WriteLine("[" + r.Replace(s, "").Trim() + "]");

This simply matches any sequence of digits that is at the end of the string and remove it (also trimmering away the last space)

This does the job:

string test = "ABStreet 10 552896";
string testWithoutLastNumber = test.Substring(0, test.LastIndexOf(' '));

I'm just not sure if it is the most elegant and/or effective way to do it. The LastIndexOf method looks for the last occurrence of a whitespace (or whatever character separator you wish to use), and then the Substring up to that position is taken. The separator itself is not included due to the first character in the string being at position/index 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM