• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

Obtaining Values in a string

Hi All,

This is such a silly question, but how would i obtain the two values lat and lang in the string below, im looking at the two lat and lang values in center.

viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},

Thanks

Nick
0
Jetski5822
Asked:
Jetski5822
1 Solution
 
devsolnsCommented:
I would use regular expressions to parse the results out of the string.
0
 
Jetski5822Author Commented:
I have been trying but i jsut dont understand Regex very well, any ideas?
0
 
neilpriceCommented:
Hi,

You could try the following quickly knocked up regex...

(using System.Text.RegularExpressions;)

Regex r = new Regex(@".*center:.*{lat: ([-0123456789.]*),lng: ([-0123456789.]*).*lat");

Then using the r.Match(yourstring).Group[1] for lat value and r.Match(yourstring).Group[2] for lng value.
e.g.
Console.WriteLine("lat=" + r.Match(@"viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},").Groups[1].ToString());
Console.WriteLine("lng=" + r.Match(@"viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},").Groups[2].ToString());


Hope this helps,
Neil
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
The old fashioned way...

            String input = "viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},";

            decimal lat = 0;
            decimal lng = 0;
           
            int center = input.IndexOf("center:");
            int leftBrace = input.IndexOf("{", center);
            int rightBrace = input.IndexOf("}", center);
            String data = input.Substring(leftBrace + 1, rightBrace - leftBrace - 1);
           
            String[] values = data.Split(",".ToCharArray());          
           
            String[] decimalValue = values[0].Split(":".ToCharArray());
            lat = decimal.Parse(decimalValue[1]);

            decimalValue = values[1].Split(":".ToCharArray());
            lng = decimal.Parse(decimalValue[1]);

            MessageBox.Show(lat.ToString() + Environment.NewLine + lng.ToString());
0
 
Jetski5822Author Commented:
Awsome guys, thanks alot.. i changed it slightly.. as its much quicker now.

Regex regVal = new Regex(@"center: {lat: ([-0-9.]*),lng: ([-0-9.]*)},", RegexOptions.IgnoreCase|RegexOptions.Compiled);

Many thanks Nick
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now