开发者

C# Read Specific Line in Test

开发者 https://www.devze.com 2023-04-11 18:10 出处:网络
I\'m using an api that returns results like this: OK 66443010 http://getclicky.com/help/api/whitelabel Using C# what is the best way to get the value of a specific line, like the 2nd line.

I'm using an api that returns results like this:

C# Read Specific Line in Test

OK

66443010

http://getclicky.com/help/api/whitelabel

Using C# what is the best way to get the value of a specific line, like the 2nd line. I just want the &开发者_开发问答quot;500"


It can be as simple as this (assuming that the lines are separated with "\n", you should check this with your return value):

var lines = result.Split("\n");
var code = lines.Length >= 2 ? lines[1] : null;


The example below uses regular expressions to split the string based on every occurence of a sequence of carriage return or newline characters:

var segments = Regex.Split(myText, @"[\r\n]+");

From this you can just grab whichever segment you want by indexing the result, and it doesn't rely on any specific newline character from the remote API.

This approach also has the advantage of removing any blank lines from the segments array, which (presumably) you aren't interested in.


Use ReadLine() of StreamReader or File.ReadAllLines to populate a string[], then you'll pull the line you desire from the array. For the second line, pull string at index 1.

If you have the data already in a string, use string.Split(Environment.NewLine) to make the string[].


Thanks for your help. With your feedback I made this function:

private static string GetLineFromResponse(string response, int lineWanted)
    {
        var lines = response.Split('\n');
        return lines[lineWanted];
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号