我正在尝试从拆分字符串中删除元素/项/条目.
假设我得到了string[ string_ ]如下:
string string_ = "one;two;three;four;five;six";
Run Code Online (Sandbox Code Playgroud)
然后我拆分这个字符串来得到每一个,比方说,项目:
string[] item = (string_.Split(";"));
Run Code Online (Sandbox Code Playgroud)
除变量外我没有其他信息.根据用户的选择,我可以获得项目值和索引.
假设对于这个例子,用户选择" 4 ",即索引" 3 ".
如何使我的字符串看起来像索引3已被删除,因为string_它将等于以下内容:
"一;二;三;五;六"
我尝试了多种方法,似乎唯一的解决方案是通过char方法.
是真的还是我错过了什么?
编辑建议已经_posted_answer:根据用户选择,我的ITEM可以放在我的分割字符串中的任何位置,这个问题不完全相同.
首先,你需要写出更好的变量名,string_是一个可怕的名字.甚至像"输入"之类的东西也更好.
string input = "one;two;three;four;five;six";
Run Code Online (Sandbox Code Playgroud)
接下来,您使用的是正确的轨道Split().这将返回一个数组string:
string[] splitInput = input.Split(";");
Run Code Online (Sandbox Code Playgroud)
生成的字符串数组将如下所示:
//string[0] = one
//string[1] = two
//string[2] = three
//string[3] = four
//string[4] = five
//string[5] = six
Run Code Online (Sandbox Code Playgroud)
如果要从数组中删除特定元素,可以List<T>使用ToList()而不是使用结果的RemoveAt()方法来生成Split()a 的结果List<T>:
List<string> splitList = input.Split(';').ToList();
splitList.RemoveAt(3);
//Re-create the string
string outputString = string.Join(";", splitList);
//output is: "one;two;three;five;six"
Run Code Online (Sandbox Code Playgroud)
如果您需要从列表中删除项目而不知道其索引但知道实际字符串,则可以使用LINQ Where()过滤掉匹配的项目:
//Get the input from the user somehow
string userInput = Console.ReadLine();
IEnumerable<string> filteredList = input.Split(';')
.Where(x => string.Compare(x, userInput, true) != 0);
//Re-create the string
string outputString = string.Join(";", filteredList);
Run Code Online (Sandbox Code Playgroud)
我做了一个小提琴证明这两种方法在这里