skip to Main Content

i want to parse a string to get second last character from a string. Here is what i am trying to parse

[XX] G_RIMN_4000+_OLEPHI_700+ [InstalmentScheme 1]

From above string i want to get the second last character whether it is single digit or double digit
so e.g 1] i want 1 or 26] i want 26

I tried following approach

string input = "[XR] Z_Prem_4000+_Delphi_700+ [InstalmentScheme 1]";

var words = input.Split(' ');
var reqWord = "";
if(words.Length > 1)
   reqWord = words[words.Length-1];
        Console.WriteLine (reqWord);

i am getting 1] as result but i want whatever digit before last ] in a string

2

Answers


  1. You can parse the string using a regular expression, like this:

    string input = "[XR] Z_Prem_4000+_Delphi_700+ [InstalmentScheme 1]";
    
    var match = Regex.Match(input, @"(d+)]$"); // gets the digits before ] at the end of the string
    var reqWord = "";
    if (match.Success)
    {
        reqWord = match.Groups[1].Value;
    }
    Console.WriteLine (reqWord);
    
    Login or Signup to reply.
  2. Without using RegularExpressions you can write this

    // Take the position of the last space
    int pos = input.LastIndexOf(' ');
    
    // Extract the number from that pos and remove the final ]
    string number = input.Substring(pos).TrimEnd(']');
    
    // Eventually convert it to an integer
    Int32.TryParse(number, out int value);
    
    Console.WriteLine(value);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search