简体   繁体   English

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

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

I'm having a string of coordinates with [Lat, Lng] format.我有一个[Lat, Lng]格式的坐标字符串。

How can I convert it to [Lng, Lat] format in C#?如何将其转换为 C# 中的[Lng, Lat]格式?

For example:例如:

Input:输入:

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

Output: Output:

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

Start by splitting the string into parts each containing a number (as string):首先将字符串分成多个部分,每个部分都包含一个数字(作为字符串):

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

Then create pairs of numbers as ValueTuples:然后将数字对创建为 ValueTuples:

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

Finally, join these number pairs as inverted to form new coordinates:最后,将这些数字对倒置以形成新坐标:

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

If you want to do more than just create a new string, then convert the coordinates to an appropriate data structure and don't work with strings.如果您想做的不仅仅是创建一个新字符串,那么请将坐标转换为适当的数据结构并且不要使用字符串。 Eg you could declare a coordinate as例如,您可以将坐标声明为

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])));
    }
}

and then do the conversion with然后进行转换

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

Now you can do a lot of other useful things with the coordinates.现在你可以用坐标做很多其他有用的事情。

When you're manipulating a set of data for a specific purpose, it's often the case that using a class to manage it makes the rest of the work easier.当您为特定目的操作一组数据时,通常使用 class 来管理它会使 rest 的工作更容易。 If you're doing anything more than just re-arranging the string, implementing something like this is usually the best way to go (NOTE: this is a simplified example and obviously does very little data-integrity/safety testing beyond null data, and range checking, but the string parsing should be fairly resilient:):如果您要做的不仅仅是重新排列字符串,那么实现这样的事情通常是 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 );
}

To do what you want, simply parse your source data through that class and use the .Swap() function:要做你想做的,只需通过 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 += "]";

First you need to trim off the open and closed square brackets and split the string by ],[ to get each set of coordinates.首先,您需要修剪开方括号和闭合方括号,并用 ],[ 分割字符串以获取每组坐标。

Then you loop over each of those and split by comma to separate the lat and long.然后你遍历每一个并用逗号分隔以分隔纬度和经度。 To make things easier, create a simple data container for those values.为了使事情更容易,为这些值创建一个简单的数据容器。 Since they go back to string you can make those values as strings, in my example I parse to float.由于它们 go 回到字符串,您可以将这些值作为字符串,在我的示例中,我解析为浮点数。

After you have all of your elements properly parsed out, you can reconstruct the string again.在正确解析完所有元素后,您可以再次重建字符串。

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