I'm using c#. I need a method that will take a string as input, search for the percent symbol in that string, then return the number directly in front of the percent symbol. for example "asdf sdfa asf 32% asdf"
would return 32. "asdfl asfi asdf kd 34.5% adsfkjfg"
would return 34.5. I know how to find the index of the percent symbol then loop backwards searching for a space, and return everything in the middle. I feel there is probably a more efficient way to do it.
var result = str.Split(' ')
.Where(s => s.Contains('%'))
.Select(s => s.Trim('%'));
Explanation
Split turns your input string into an IEnumerable<string>
, Where selects only those strings that contain the searched character %
and Select projects each of those elements, such that the new elements do not contain the character %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With