如何将地理坐标字符串数组转换为交换值的2D数组?
解决方案
假设你的原始坐标数据是一个字符串数组(每行对应一组坐标,末尾带有逗号),可以通过以下步骤转换为交换顺序后的二维字符串数组:
步骤说明
- 清理字符串: 移除每个坐标字符串末尾的逗号和多余空格,避免分割时出现无效元素。
- 分割坐标: 将每个清理后的字符串按空格分割为两个坐标值。
- 交换顺序: 反转两个坐标值的位置(原纬度在前,转换后经度在前)。
- 转换为二维数组: 将处理后的交错数组转换为你需要的
string[,]类型二维数组。
代码实现
1. 定义原始输入数组
string[] rawCoordinates = new[] { "32.28057860000054 -174.8307036999996,", "33.03439570061262 -174.82691533618038,", "33.15555942151208 -174.8255452254468,", "33.161189722126196 -174.825486109871,", "33.16405200490681 -174.82544919191812,", "33.22284105148913 -174.824784409563,", "33.32412188155387 -174.82338459780988,", "33.341040408962115 -174.8231663812863" };
2. 处理并转换为二维数组
// 先处理每个坐标,得到交错数组 var processedCoords = rawCoordinates .Select(coord => coord.TrimEnd(',', ' ') // 移除末尾的逗号和空格 .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) // 分割为两个坐标值 .Reverse() // 交换顺序 .ToArray()) .ToArray(); // 转换为string[,]二维数组 string[,] result = new string[processedCoords.Length, 2]; for (int i = 0; i < processedCoords.Length; i++) { result[i, 0] = processedCoords[i][0]; result[i, 1] = processedCoords[i][1]; }
3. 可选:转换为数值类型二维数组
如果你的坐标需要用于计算,建议转换为double[,]类型:
double[,] numericResult = new double[processedCoords.Length, 2]; for (int i = 0; i < processedCoords.Length; i++) { // 这里可以根据需求添加格式验证,避免转换失败 numericResult[i, 0] = double.Parse(processedCoords[i][0]); numericResult[i, 1] = double.Parse(processedCoords[i][1]); }
4. 格式验证(可选)
如果担心原始数据存在格式错误,可以添加验证逻辑:
var processedCoords = rawCoordinates .Select(coord => { var cleaned = coord.TrimEnd(',', ' '); var parts = cleaned.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { throw new FormatException($"无效的坐标格式: {coord}"); } return parts.Reverse().ToArray(); }) .ToArray();
内容的提问来源于stack exchange,提问作者KJSR
相关产品推荐
相关产品推荐

