Break a line into the last N separator numbers

I need help developing logic for line splitting, but only based on the last two line breaks.

Input Example:

string s1 = "Dog \ Cat \ Bird \ Cow";

string s2 = "Hello \ World \ How \ Are \ You";

string s3 = "I \ am \ Peter";

Expected results:

string[] newS1 = "Dog Cat", "Bird", "Cow"
string[] newS2 = "Hello World How", "Are", "You"
string[] newS3 = "I", "am", "Peter"

So, as you can see, I want to split the line into the last 2 "\", and everything else until the last 2 "\" will be combined into one line.

I tried the .Split method, but it just split each "\" in the string.

Edited: if the line has less than 2 "\", it will simply be split into everything that it has

Updates: Wow, this is a bunch of interesting solutions! Thank you very much!

+4
source share
6 answers

Try the following:

var parts = s1.Split(new[] { " \\ " }, StringSplitOptions.None);
var partsCount = parts.Count();
var result = new[] { string.Join(" ", parts.Take(partsCount - 2)) }.Concat(parts.Skip(partsCount - 2));
+5
source

regex:

var output = Regex.Split(input, @"\s*\\\s*([^\\]*?)\s*\\\s*(?=[^\\]*$)");

, , .

"Dog \ Cat \ Bird \ Cow" { "Dog \ Cat", "Bird", "Cow" }. \ , :

output[0] = output[0].Replace(" \\", "");

. :

var output = Regex.Split(str, @"\s*\\\s*([^\\]*?)\s*\\\s*(?=[^\\]*$)|(?<=^[^\\\s]*)\s*\\\s*(?=[^\\\s]*$)");

. , , "~" "%", :

var output = Regex.Split(str, @"(?:[%~\s\\]+([^%~\s\\]+?)[%~\s\\]+|(?<=^[^%~\s\\]+)[%~\s\\]+)(?=[^%~\s\\]+$)");

, [%~\s\\] , [^%~\s\\] . , \s 'whitespace' character.

, :

var output = Regex.Split(str, @"(?:\W+(\w+)\W+|(?<=^\w+)\W+)(?=\w+$)");

\w 'word' (, ) \w -.

+6

, Split <space>\<space>:

string input = @"Dog \ Cat \ Bird \ Cow";
string[] parts = input.Split(new string[]{@" \ "}, 
    StringSplitOptions.None);

Join , :

// NOTE: Check that there are at least 2 parts.
string part0 = String.Join(" ", parts.Take(parts.Length - 2));
string part1 = parts[parts.Length - 2];
string part2 = parts[parts.Length - 1];

, .

string[] newParts = new []{ part0, part1, part2 };

:

new [] { "Dog Cat", "Bird", "Cow" }
+3

split, N-2 , 3- , Join, - N-1 - N . , , .

+2

. :

String[] tokens = theString.Split("\\");
String[] components = new String[3];
for(int i = 0; i < tokens.length - 2; i++)
{
    components[0] += tokens[i];
}

components[1] = tokens[tokens.length - 2];
components[2] = tokens[tokens.length - 1];
+2

, . 2 , -1.

, var -1, , .

var -1, 2 , .

Create an array of 3 lines, separated using information from two vars, return.

Hope you understand my pseudo code, give me a comment if you need any help.

0
source

Source: https://habr.com/ru/post/1527773/


All Articles