-3

I have some strings like " 8 2 / 5", "5 5/ 7" and so on, containg math fractions. I need to convert them into doubles. So, how can I get these parts " 8 " "2 / 5", into variables?

var src = " 8 2 /  5";
string base = getBase(src);
string frac = getFrac(src);
// Now base must contain "8" and frac "2/5";

I don't know if some stuff could do this "fraction-to-double" task is already exist (if so, give a link or something), but if I could get these parts into variables I would be able to perform a division and an addition at least.

Tomcat
  • 35
  • 5

2 Answers2

0

The simplest approach would be a regex like

(\d) (\d) \/ (\d)

which will work with single digits and all spaces are set correctly. To code to calculate the result could look like

string src = "8 2 / 5";

Regex rx = new Regex(@"(\d) (\d) \/ (\d)");
Match m = rx.Match(src);

if (m.Success)
{
    int bs = Convert.ToInt32(m.Groups[1].Value);
    int f1 = Convert.ToInt32(m.Groups[2].Value);
    int f2 = Convert.ToInt32(m.Groups[3].Value);

    double result = bs + (double)f1 / f2;
}

To allow usage of multiple digits and multiple spaces between your numbers you could improve the regex like

(\d*)\s+(\d*)\s+\/\s+(\d*)

To test regexes you can use som online tools like regex101.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • m.Groups[1].Value is what I need. It helps to extract needed part of string, thanks for regex templates though. P.S. Why people minus my question? I'm newbee and I have no idea how to handle regexps. I'll study, but now I need to get a quick tip. It would've taken a lot of time to dig out m.Groups[1].Value expression if you hadn't told me. What's wrong with people... – Tomcat Aug 12 '18 at 11:59
  • Glad I could help. Try to add some of the code you tried to your future questions. This improves your questions a lot and you will get better and more help because other people can see your effort. – Fruchtzwerg Aug 12 '18 at 13:15
0

Simple Operations : the Regex tested on RegexStorm

String src = " 8 2 /  5";
String Regex = @"([1-9])([0-9]*)([ ])([1-9])([0-9]*)((.)([0-9]+)|)([ ])([- / + *]){1}([ ])([1-9])([0-9]*)((.)([0-9]+)|)";

if(!Regex.IsMatch(src , Regex ))
   return;


float Base = float.Parse(Base.Split(" ")[0], CultureInfo.InvariantCulture.NumberFormat);
float Devided= float.Parse(Base.Split(" ")[1], CultureInfo.InvariantCulture.NumberFormat);
float Operator= float.Parse(Base.Split(" ")[2], CultureInfo.InvariantCulture.NumberFormat);
float Denominator= float.Parse(Base.Split(" ")[3], CultureInfo.InvariantCulture.NumberFormat);

//TODO your operation here
lagripe
  • 766
  • 6
  • 18