Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string for percentage [closed]

Tags:

string

c#

parsing

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.

like image 494
imjustaboy Avatar asked Oct 20 '25 03:10

imjustaboy


1 Answers

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 %

like image 160
mihai Avatar answered Oct 21 '25 17:10

mihai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!