Reputation: 107
I want to get the "2" character behind "- 60000 rupiah". So i tried to code it with substring :
string s = "Ayam Bakar - 30000 x 2 - 60000 rupiah";
string qtyMenu = s.Substring(s.IndexOf("x") + 1, s.IndexOf("-") - 1);
But the substring end index didn't work properly. Maybe because the sentences have multiple "-" character. Is it possible to get different index of same character in that senteces ?
Upvotes: 1
Views: 146
Reputation: 906
This is a good situation for Regex
string s = "Ayam Bakar - 30000 x 2 - 60000 rupiah";
// "x" followed by (maybe) whitespaces followed by at least one digit followed by (maybe) whitespaces followed by "-".
// Capture the digits with the (...)
var match = Regex.Match(s, @"x\s*(\d+)\s*\-");
if (match.Success)
{
// Groups[1] is the captured group
string foo = match.Groups[1].Value;
}
Upvotes: 4
Reputation: 51440
From the message, I can derive the template format: "{Product Name} - {Price x Qty} - {Subtotal}"
So you can implement this solution:
// Split message by '-'
var messages = s.Split('-');
// Result: messages[0] = "Ayam Bakar"
// Result: messages[1] = " 30000 x 2 "
// Result: messages[2] = " 60000 rupiah"
// Obtain {Price x Qty} in messages[1] and get the value after 'x'
var qtyMenu = messages[1].Substring(messages[1].IndexOf("x") + 1).Trim();
Upvotes: 1
Reputation: 5453
You can easily achieve this by following technique:
string s = "Ayam Bakar - 30000 x 2 - 60000 rupiah";
string qtyMenu = s.Substring(s.IndexOf("x") + 1, (s.LastIndexOf("-")) - (s.IndexOf("x") + 1));
For the second parameter, the length of the the string to extract is determined by the last index of -
minus the index of x
Upvotes: 3