0

Follow string:

11 blabalba, balbalba balballbal  baba
12 balbal13, afafaf14 1414adad1414 12 12

I want it to return something like this (separated by split):

array 0: 11
array 1: blabalba, balbalba balballbal  baba

Second line:

array 0: 12
array 1: balbal13, afafaf14 1414adad1414 12 12

How to make a split in the first position?

1
  • Does your string occured in new line? If occured in new line you can split by \n probably. Commented Nov 8, 2017 at 2:27

3 Answers 3

2
var input = "11 blabalba, balbalba balballbal  baba";
var split = input.Split(new [] {' '}, 2);

It splits the original string by spaces but returns a maximum of two strings. So it's only going to split using the first space.

string.Split documentation

Sign up to request clarification or add additional context in comments.

4 Comments

Your example made it look like you have a string that starts with a number, followed by a space, followed by more text. Whatever the first "word" is - the first text segmented by a space - that's what's going to go in the first array element. Where it came from or whether it's random won't matter. So if the string is "124 ABC 123" you'll get ["124", "ABC 123"].
What is number 2? input.Split (new [] {''}, 2);
The number two tells it how many elements to split the string into. If I left out the 2 then it would split "124 ABC 123" wherever there is a space, giving you an array of three elements. The 2 tells it to only return 2 elements. It will split the string on the first space, giving you a maximum of two elements, and ignore the rest of the spaces.
Beautiful to your reply :)
1
            var content = "11  blabalba, balbalba balballbal  baba";

            var splitContent = content.Split(' ');

            splitContent[1] = string.Join(" ", splitContent.Skip(1).Take(splitContent.Length - 1).ToArray());

            splitContent = splitContent.Take(2).ToArray();

Comments

1
var head = string.Join("", s.TakeWhile(x => char.IsDigit(x)));
var rest = string.Join("", s.Skip(head.Length + 1));

return new [] { head, rest };

Or more robustly:

var regex = new Regex(@"^(?'head'\d+)\s(?'rest'.+)$");

var match = regex.Match(s);

var head = match.Groups["head"].Value;
var rest = match.Groups["rest"].Value;

return new [] { head, rest};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.