Tyler Cline
Tyler Cline

Reputation: 1

Converting a String of input into Inches

What I would like to do is to take input string, in architectural format and convert it to a double in inches. For example:

Input: (String)    Output: (Double)

1'-2"              14    
1'-2 1/2"          14.5    
1'2 3/16"          14.1875    
1'                 12    
12                 12    
12"                12    
1'0.5              12.5    
1'0.5"             12.5    
1'-0.5             12.5    
1'-0.5"            12.5

I know I would need to iterate through every character in the string and test a bunch of cases but I did not know if there was some built in function within c# or within some other resource that could do this for me and not make me re-invent the wheel.

Upvotes: 0

Views: 360

Answers (1)

Kevin
Kevin

Reputation: 2243

Regex for the win!

Okay, if you're new to Regex, it's basically a way of parsing strings. So, realistically, what does your input consist of?

At a high level, you've got one of these three possibilities:

  1. Composite: Number, followed by ', followed by either a - or space, followed by a number, and optionally ending with a "
  2. Feet Only: Number, followed by a '
  3. Inches Only: Number, optionally followed by a "

And those 'Number's?

Possibilities:

  • 1+ digits (aka, "23")
  • 1+ digits, a '.', and 1+ digits (aka, "32.43")
  • 1+ digits, a space, 1+ digits, a slash, and 1+ digits (aka, "32 13/16")
  • 1+ digits, a slash, and 1+ digits (aka, "13/16")

Okay, so first up, we need a regex for one of your "numbers":

\d+|\d+.\d+|\d+ \d+\/\d+|\d+\/\d+

(Looks complicated, but see these two pages for reference: http://www.rexegg.com/regex-quickstart.html and https://regex101.com/)

Now, just so our regex'es don't get too complicated, you could do something like this:

string regexSnippetForNumber = @"\d+|\d+.\d+|\d+ \d+\/\d+|\d+\/\d+";
string regexForComposite = 
    "^(" + regexSnippetForNumber + ")'[ -]" + 
    "(" + regexSnippetForNumber + ")\"?$"

... and then, if the input matches regexForComposite, you use the two capturing groups to get the two numbers. (Which you'd have to parse to get the numerical value.)

Hopefully that makes sense and can get you close enough to the finish line. If you've never used Regexes before, I highly suggest you read up on them. They're incredibly handy when you need to do string parsing that can otherwise be really annoying (like this exact problem!)

Upvotes: 1

Related Questions