Home > front end >  How to get last char(s) of a string in C#
How to get last char(s) of a string in C#

Time:11-17

Could someone please help me to have a method in C# to return a string as this example:

input string: 21-0001 --> return 1
input string: 21-0025 --> return 25
input string: 21-0150 --> return 150

Thank you very much.

CodePudding user response:

You can try using regular expression:

Code:

 using System.Text.RegularExpressions;

 ...

 string result = Regex.Match(input, "(?:[1-9][0-9]*|0)$").Value;

Pattern explained: (?:[1-9][0-9]*|0)$

  (?:            - group start
    [1-9][0-9]*  - one digit in 1..9 rangem followed by digits in 0..9 range
  |              - or
  0              - single 0
  )              - end of group
  $              - end of string

Demo:

string[] tests = new string[] {
  "21-0000", // let's add all zeroes case...
  "21-0001",
  "21-0025",
  "21-0150",
  "21-1234", // ...and no zeroes case
};

string demo = string.Join(Environment.NewLine, tests
  .Select(test => $"{test} --> {Regex.Match(test, "(?:[1-9][0-9]*|0)$").Value}"));

Console.Write(demo);

Outcome:

21-0000 --> 0
21-0001 --> 1
21-0025 --> 25
21-0150 --> 150
21-1234 --> 1234

CodePudding user response:

It could be something like:

String s = "21-0150";
int result = Int32.Parse(s.Substring(s.LastIndexOf('-')   1));

CodePudding user response:

You can use Regexp on System.Text.RegularExpressions namespace.

Docs link if you want to know more about the subject.

var regexp = new System.Text.RegularExpressions.Regex(@"(?<=(-|[0] ))\d $");

var match = regexp.Match("21-0001");

if (match.Success)
{
    Console.WriteLine(match.Value);   
}

CodePudding user response:

You asked for a method that returns the result as a string:

    private string MyMethod(string input)
    {
        return input.Split("-").Last().TrimStart('0');
    }

It takes the last part of the string after the last "-" and removes the leading zeros.

CodePudding user response:

Try this:

static string GetResult(string i) {
    return int.TryParse(i.Substring(i.IndexOf('-')   1), out int r) ? r.ToString() : string.Empty;
}
  • Related