简体   繁体   English

C#分割字符串

[英]c# split string

I have this code that splits a specific string. 我有这段代码可以拆分特定的字符串。

str = "\n\nThis\nString\nis\nsplit\ninto\narray";
string[] delimiterChar = { "\n" };

var splitArray = str.Split(delimiterChar);

The split array is simple array of strings, but why isn't it possible to remove the first 2 item by using: split数组是简单的字符串数组,但是为什么不能通过使用以下命令删除前两个项:

splitArray[0].remove();
splitArray[0].remove();

If you need to remove empty entries, then just specify it in the split method. 如果需要删除空条目,则只需在split方法中指定它。 There is no need to remove them manually. 无需手动删除它们。

var splitArray = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries);

If you want to specifically remove certain specific elements, then you can convert the array (non-mutable) to a list (mutable), and work on it like: 如果要专门删除某些特定元素,则可以将数组(非可变的)转换为列表(可变的),并像下面这样处理它:

var splitList = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries).ToList();
splitList.RemoveAt(0);

This might be one of the solution which might get the desired result. 这可能是可能获得期望结果的解决方案之一。

string str = "\n\nThis\nString\nis\nsplit\ninto\narray";
str = str.TrimStart('\n');
var splitArray = str.Split('\n');

yes,but sometimes the string contains random string at the first 3 indexes.. so i want to split this simple string into Array via Split and remove . 是的,但是有时该字符串在前3个索引处包含随机字符串..因此,我想通过Split和remove将这个简单的字符串拆分为Array。

The split array is simple array of strings, but why isn't it possible to remove the first 2 items split数组是简单的字符串数组,但是为什么不能删除前2个项目

Split it and then skip whatever number of items you wish using Linq: 拆分它,然后使用Linq跳过任何数量的项目:

// I am skipping 3 for example
var splitArray = str.Split(delimiterChar).Skip(3).ToList();

Make sure to add this to the list of using statements: 确保将其添加到using语句列表中:

using System.Linq;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM