繁体   English   中英

将字符串转换为数组并交换 c# 中元素的两个值?

[英]Convert string to an Array and swap two value of an elments in c#?

我有一个[Lat, Lng]格式的坐标字符串。

如何将其转换为 C# 中的[Lng, Lat]格式?

例如:

输入:

string LatLng = "[[12.06, 106.67],[12.67, 106.68], ... ]" //string

Output:

var LatLng = "[[106.67, 12.06],[106.68, 12.07], ... ]"

首先将字符串分成多个部分,每个部分都包含一个数字(作为字符串):

string LatLng = "[[12.06, 106.67],[12.67, 106.68],[11, 22]]";
string[] parts =
    LatLng.Split(new[] { '[', ']', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

然后将数字对创建为 ValueTuples:

var coordinates = Enumerable.Range(0, parts.Length / 2)
    .Select(i => (parts[2 * i], parts[2 * i + 1]));

最后,将这些数字对倒置以形成新坐标:

string mapBoxCoords =
    "[" + String.Join(", ", coordinates.Select(c => $"[{c.Item2}, {c.Item1}]")) + "]";

如果您想做的不仅仅是创建一个新字符串,那么请将坐标转换为适当的数据结构并且不要使用字符串。 例如,您可以将坐标声明为

public struct Coordinate
{
    public Coordinate(decimal latitude, decimal longitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public decimal Latitude { get; }
    public decimal Longitude { get; }

    public string ToLatLngString() => $"[{Latitude}, {Longitude}]";

    public string ToLngLatString() => $"[{Longitude }, {Latitude}]";

    public static IEnumerable<Coordinate> FromLatLngFormat(string latLng)
    {
        string[] parts = latLng.Split(
            new[] { '[', ']', ',', ' ' }, 
            StringSplitOptions.RemoveEmptyEntries);

        return Enumerable.Range(0, parts.Length / 2)
            .Select(i => new Coordinate(Decimal.Parse(parts[2 * i]),
                                        Decimal.Parse(parts[2 * i + 1])));
    }
}

然后进行转换

var coordinates = Coordinate.FromLatLngFormat(LatLng);
string mapBoxCoords =
    "[" + String.Join(",", coordinates.Select(c => c.ToLngLatString())) + "]";

现在你可以用坐标做很多其他有用的事情。

当您为特定目的操作一组数据时,通常使用 class 来管理它会使 rest 的工作更容易。 如果您要做的不仅仅是重新排列字符串,那么实现这样的事情通常是 go 的最佳方法(注意:这是一个简化的示例,显然除了 null 数据之外,几乎没有进行数据完整性/安全性测试,并且范围检查,但字符串解析应该相当有弹性:):

class LatLong {
    // Properties
    //
    protected decimal _lat  = 0.0M;
    protected decimal _long = 0.0M;

    // Facilitates validating that strings contain values between -180.0.. and 180.0...
    protected static const string PATTERN = /* language=regex */
        @"^[-+]?(0?[\d]{1,2}([.][\d]*)?|1[0-7][\d]([.][\d]*)?|180([.]0*)?)$";

    // Accessors
    //
    public decimal Latitude 
    { 
        get => _lat;
        set => _lat = Math.Max( Math.Min( 180.0M, value ), -180.0M );
    }

    public decimal Longitude
    { 
        get => _long;
        set => _long = Math.Max( Math.Min( 180.0M, value ), -180.0M );
    }

    // Methods
    //
    public LatLong Swap() => new LatLong() { Longitude = _long, Latitude = _lat };

    public override string ToString() => $"[{Latitude}, {Longitude}]";

    public static LatLong Parse( string data )
    {
        // This function expects data in the form of "###.##, ###.##"
        // with any amount of other non-numeric data sprinkled in. As long as there
        // are two decimal values ranging between -180.0 and +180.0, and
        // separated by a comma, this should be able to parse it.

        if (string.IsNullOrWhiteSpace( data )
            throw new ArgumentException( "Invalid data!" );

        // remove any cruft and split the values
        string[] work = Regex.Replace( data, @"[^-.\d,]", "" ).Split( new char[] { ',' } );

        LatLong result = new LatLong();
        if (work.Length > 0)
            result._lat  = IsValidValue( work[ 0 ] ) ? decimal.Parse( work[ 0 ] ) : 0.00M;

        if (work.Length > 1)
            result._long = IsValidValue( work[ 1 ] ) ? decimal.Parse( work[ 1 ] ) : 0.00M;

        return result;
    }

    public static bool IsValidValue( string test ) =>
        !string.IsNullOrWhiteSpace( test ) && Regex.IsMatch( test.Trim(), PATTERN, RegexOptions.ExplicitCapture );
}

要做你想做的,只需通过 class 解析源数据并使用.Swap() function:

string LatLng = "[[12.06, 106.67],[12.67, 106.68], ... ]", output = "[";
foreach( string s in LatLng.Split( "],[", StringSplitOptions.RemoveEmptyEntries ) )
    output += ((output.Length > 1) ? "," : "") + LatLong.Parse( s ).Swap().ToString();

output += "]";

首先,您需要修剪开方括号和闭合方括号,并用 ],[ 分割字符串以获取每组坐标。

然后你遍历每一个并用逗号分隔以分隔纬度和经度。 为了使事情更容易,为这些值创建一个简单的数据容器。 由于它们 go 回到字符串,您可以将这些值作为字符串,在我的示例中,我解析为浮点数。

在正确解析完所有元素后,您可以再次重建字符串。

private class LatLong
{
    public LatLong(decimal lat, decimal @long)
    {
        Lat = lat;
        Long = @long;
    }

    public decimal Lat { get; set; }
    public decimal Long { get; set; }
}
private void SplitLatLong()
{
    var originalString = "[[24.5, 111.232],[51.2, 112.3],[12, 54.1]]";
    var outputList = new List<LatLong>();

    var itemsSplit = originalString
        .TrimStart(new char[] { '[' })
        .TrimEnd(new char[] { ']' })
        .Split(new string[] { "],[" }, StringSplitOptions.RemoveEmptyEntries);

    foreach (var item in itemsSplit)
    {
        var latLongSplit = item
            .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        outputList.Add(new LatLong(
            decimal.Parse(latLongSplit[1]),
            decimal.Parse(latLongSplit[0]))
        );
    }

    var remerged = "[[" + string.Join("],[", outputList.Select(o => o.Lat + ", " + o.Long)) + "]]";

    // Output the value to make sure it was correct (i am in winforms atm)
    //
    MessageBox.Show(originalString + "\r\n" + remerged);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM