Reputation: 453
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.
Upvotes: 2
Views: 5967
Reputation: 390
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];
Upvotes: 0
Reputation: 11480
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.
Upvotes: 3
Reputation: 8907
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}";
Upvotes: 6