简体   繁体   中英

C# How to turn String with Carriage Return symbols in to an array

I am calling some external method that returns a string like this.

"[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]"

How do I turn this in to an Array with the values 1,2,3 ?

Should I be trying to split/substring methods to do this, or is there some kind of built in .net method that can do this?

I have tried,

string theStringResult = Class.ExternalMethod();
theStringResult.ToArray()

The returned string appears to be a JSON array made up of strings.

The line breaks are part of a pretty print version of the JSON string which, when not escaped, would look like this...

[
  "0",
  "1",
  "2"
]

You can use Newtonsoft's Json.Net to parse and deserialize the returned string into a strongly typed object.

string theStringResult = Class.ExternalMethod();
string[] array = JsonConver.DeserializeObject<string[]>(theStringResult);

The above should produce the desired result

The method you're looking for is String.Split . It takes a single character as a parameter and returns an array of pieces split wherever that character is found.

In your case you have two characters ( "\\r\\n" ) so either you split and post-process the array, or you replace the pair with a single character and then split.

In code it looks like this:

string source = "\r\n0\r\n1\r\n2\r\n";
string parts = source.Replace("\r\n", "\n").Split('\n');

The resultant array is ["0", "1", "2"] .


Oh, that's a literal JSON string... that wasn't entirely clear on first viewing.

If the array is fairly consistent you could do string manipulation, but it's not ideal.

Add the NewtonSoft.Json NuGet package to your project and use the following:

string source = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] parts = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(source);

Same output as above.

Try this.

string Originalstring = "[\r\n  \"0\",\r\n  \"1\",\r\n  \"2\"\r\n]";
string[] result = Originalstring.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

This should split a string that has a carriage return into an array and remove any empty entries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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