Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element from a split String?

Tags:

string

c#

split

I'm trying to remove an element/item/entry from a split string.

Let's say I got the string [string_] as follows:

string string_ = "one;two;three;four;five;six";

Then I split this string to get each, let's say, item:

string[] item = (string_.Split(";"));

I have no informations other than from variables. Depending on the user choice, I can get an item value and index.

Let's say that for this example, the user chose "four" which is the index "3".

How can I make my string look like the index 3 have been deleted, as string_ would be equal to the following:

"one;two;three;five;six"

I've tried multiple things and it seems like the only solution is to go through a char method.

Is that true or did I miss something?


EDIT to suggested already_posted_answer : Not quite the same question as my ITEM could be placed anywhere in my splitted string depending on the user selection.

like image 243
Bo. Ga. Avatar asked Feb 16 '18 20:02

Bo. Ga.


1 Answers

First of all you need to write better variable names, string_ is a horrible name. Even something like "input" is way better.

string input = "one;two;three;four;five;six";

Next, you are on the right track by using Split(). This will return an array of string:

string[] splitInput = input.Split(";");

The resulting string array will look like this:

//string[0] = one
//string[1] = two
//string[2] = three
//string[3] = four
//string[4] = five
//string[5] = six

Removing with known index

If you want to remove a specific element from the array, you could make the result of Split() a List<T> by using ToList() instead and utilize the RemoveAt() method of the resulting 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"

Remove all strings that match an input

If you need to remove items from the list without knowing their index but knowing the actual string, you can use LINQ's Where() to filter out the matching items:

//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);

I made a fiddle to demonstrate both methods here

like image 136
maccettura Avatar answered Oct 19 '22 20:10

maccettura