简体   繁体   English

C#,从字符串中选择某些部分

[英]C#, selecting certain parts from string

In my example I have a string: "POINT (6.5976512883340064 53.011505757047068)" 在我的示例中,我有一个字符串: "POINT (6.5976512883340064 53.011505757047068)"

What I would like is to extract the two doubles from that string and place them in separate strings. 我想从该字符串中提取两个双打,然后将它们放在单独的字符串中。

I could use a StringReader , however the doubles are not fixed in length (aka the length may vary) so I can't state after which position to start selecting. 我可以使用StringReader ,但是双精度的长度不是固定的(也就是长度可能会有所不同),因此我无法说明要从哪个位置开始选择。

What I would like is to state that the first selection be made after the "(" and before the whitespace, and the second selection be made after the white space and before the ")". 我要声明的是,第一个选择是在“(”之后,空白之前,而第二个选择是在空白之后,“)”之前。 The rest of the string can be ignored. 字符串的其余部分可以忽略。

Any suggestions? 有什么建议么?

You can use the following code: 您可以使用以下代码:

var str = "POINT (6.5976512883340064 53.011505757047068)";
var nums = Regex.Replace(a, @"POINT\s*\(([^)]+)\)", "$1").Split(' ');
var x = nums[0];
var y = nums[1];
    void GetDoubles() 
    {
        string valuesWithoutBrackets = ExtractStringBetweenBrackets("POINT (6.5976512883340064 53.011505757047068)");
        string[] values = valuesWithoutBrackets.Split(" ".ToCharArray());

        //values[0] = "6.5976512883340064"
        //values[1] = "53.011505757047068"
    }

    string ExtractStringBetweenBrackets(string s)
    {
        // You should check for errors in real-world code, omitted for brevity
        var startTag = "(";
        int startIndex = s.IndexOf(startTag) + startTag.Length;
        int endIndex = s.IndexOf(")", startIndex);
        return s.Substring(startIndex, endIndex - startIndex);
    }
var point = "POINT (6.5976512883340064 53.011505757047068)";

var indexOfFirstBrace = point.IndexOf('(') + 1;
var indexOfLastBrace = point.IndexOf(')');
var coordinates = point.Substring(indexOfFirstBrace, indexOfLastBrace - indexOfFirstBrace).Split(' ');

var xCoordinate = coordinates[0];
var yCoordinate = coordinates[1];

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

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