[英]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. 我正在获得White / r提供的输出。 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[]
. 您还应该意识到,如果直接使用Linq操作字符串,它将被视为
char[]
。 So you need to ensure you do not use the same variable for a bunch of Linq while assigning values. 因此,您需要确保在分配值时不要对一堆Linq使用相同的变量。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.