简体   繁体   中英

Take string before and after 'First' space character

I have a big word inside a string. Example White wine extra offer.

I want to take 'White' in first line and 'wine extra offer in second. using this code below:

string value="White wine extra offer";
value = value.Split(' ').FirstOrDefault() + ' ' + Environment.NewLine + value.Split(' ').LastOrDefault();

I'm getting in output White/r offer. I'm taking the word after last space and no after first.

You can find the index of the first space and use substring I suppose.

string value = "White wine extra offer";

var spaceIndex = value.IndexOf(" ");

var firstLine = value.Substring(0, spaceIndex);
var secondLine = value.Substring(spaceIndex + 1);

var fullText = $"{firstLine}{Environment.NewLine}{secondLine}";

Your issue is because of how you are splitting your content. You have separated your content on a space, but then you have created an array with four different indexes. You can solve a couple of different approaches.

var sentence = "White wine extra offer";
var words = sentence.Split(' ');

var white = words.FirstOrDefault();
var wineExtraOffer = String.Join(" ", words.Skip(1));

You also should realize that if you manipulate a string directly with Linq, it will treat as a char[] . So you need to ensure you do not use the same variable for a bunch of Linq while assigning values.

Fiddle with output.

Can be done this way way :

string value="White wine extra offer";
string[] words = value.Split(' ');

// Take the first word and add break line 
value = words[0] + Environment.NewLine;

// Add the rest of the phrase
for(int i = 1; i < words.lenght; ++i)
  value += words[i];

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