Home > Back-end >  Get INT value between 2 matching chars
Get INT value between 2 matching chars

Time:12-11

I have a string that I need to separate the product ID from, is this format

shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==

I need to get 556 out of there, and in the case of say 2658 etc also possible.

First index ":" I think str.Substring(str.LastIndexOf(':') 1);

But then I dont know how to just break after the match, regex better? any help apprecaited

CodePudding user response:

string original = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
string startWithId = original.Substring(original.IndexOf("id:")   3);
string onlyId = startWithId.Split(':')[0];
Console.WriteLine(onlyId);

CodePudding user response:

string[] myitems = mystring.Split(':');

That will give you an array of strings that has been split on character ':'. So it will have:

myitems[0] == "shop"
myitems[1] == "?id"
myitems[2] == "556"

If you are looking for any integer after the string split, you can do something like:

foreach (string item in myitems)
{
    if (int.TryParse(item, out num))
    {
        // Do something with num.
    }
}

CodePudding user response:

If the string format is fixed, use the Split function

string str = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
int id = Convert.ToInt32(str.Split(':')[2]);
Console.WriteLine(id);

CodePudding user response:

with LINQ Try this

string text = "shop:?id:556:token:bmgwcGJxZEpnK2RqemhaKzdBYWZjbTVZN0xaOXh5L3pmdDBFZjQrWVVES1pmYVBXVVB6SlFhejBsNndnaHNsUA==";
    
var splitedText = text.Split(':');
    
var numbers = splitedText.Where(x => int.TryParse(x, out int number));
    
System.Console.WriteLine($"Numbers is : "   String.Join(',', numbers));
  • Related