-7

I have a string "Building1Floor2" and it's always in that format, how do I cleanly get the building number (e.g. 1) and floor number. I'm thinking I need a regex, but not entirely sure that's the best way. I could just use the index if the format stays the same, but if I have have a high floor number e.g. 100 it will break.

P.S. I'm using C#.

  • 2
    Possible duplicate of [Find and extract a number from a string](http://stackoverflow.com/questions/4734116/find-and-extract-a-number-from-a-string) – cbalos Dec 07 '15 at 19:01

3 Answers3

4

Use a regex like this:

Building(\d+)Floor(\d+)
coffee-converter
  • 967
  • 4
  • 13
2

Regex would be an ok option here if "Building" and "Floor" could change. e.g.: "Floor1Room23"

You could use "[A-Za-z]+([0-9]{1,})[A-Za-z]+([0-9]{1,})"

With those groupings, $1 would now be the Building number, and $2 would be Floor.

If "Building" and "Floor" never changed, however, then regex might be overkill.. you could use a string split

ddavison
  • 28,221
  • 15
  • 85
  • 110
0

Find the index of the "F" and substring on that.

int first = str.IndexOf("F") ;

String building = str.substring(1, first);
nicomp
  • 4,344
  • 4
  • 27
  • 60