Home > Blockchain >  String handling in c#?
String handling in c#?

Time:12-20

I have each string below :

MULTIPOLYGON(((107.067521 16.873693000000003,107.06849999999997 16.873613000000034)))

Now is there any way to group 107.067521 16.8736930000003 into a group, 107.06849999999997 16.873613000000034 into a group and in each group separate them. Example with group 107.067521 16.873693000000003 will split lat=107.067521, lng=16.873693000000003, do the same with the rest of the groups.

CodePudding user response:

With no regular expression, my approach is to find the text enclosed by the last ( and the first ), then split it using String.Split and delimiters of , and a space . Remove empty entries in case there are multiple spaces.

string example = @"MULTIPOLYGON(((107.067521 16.873693000000003,107.06849999999997 16.873613000000034)))";

int start = example.LastIndexOf('(');
int end = example.IndexOf(')');
string inside = example.Substring(start   1, end - start - 1);
string[] fields = inside.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

// Example
Console.WriteLine($"long1={fields[0]} lat1={fields[1]} long2={fields[2]} lat2={fields[3]}");

To be slightly more robust, you could do a first pass to delimit on commas to get long-lat pairs separated by spaces, and then split those fields on spaces. But assuming the input is well formed, the example above should work reasonably well.

CodePudding user response:

I think I'd use Split to do all the work:

var nums = input.Split(", ()".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

var points = new List<Point>();

for(int i = 1; i < nums.Length; i  = 2){
  points.Add(new Point {
    Lat = double.Parse(nums[i 1],
    Lon = double.Parse(nums[i])
  });
}

Note in WKT representation it's more typical to have it in "Long Lat" order - you've said the lat comes first. If you're absolutely certain your string is "Long Lat" then swap the assignments over inside the loop, but double check first otherwise you might end up drawing your polygons on a completely different part of the planet

Another thing to point out; you've only got a single poly here and if you only ever have one then simple parsing it like above will do, but the use of a multi poly is to keep track of which polygons are supposed to be kept together. Flattening to a list of points will work ok if there is only one poly, but things could go wonky if there really are multiple polys in your string eg

MULTIPOLYGON( (1 2,3 4,5 6,1 2) , (7 8,9 10,11 12,7 8) )

POLYGON( (1 2,3 4,5 6,1 2,7 8,9 10,11 12,7 8) )

These two are completely different shapes (and the latter doesn't close).. Take care with it, and consider a more involved parsing routine if you truly have multi polys

  • Related