Sleep Paralysis
Sleep Paralysis

Reputation: 469

Trim space in <list>string C#

I am working on an application where I have multiple ID in a string that I passed from my view separated by a ';'.
So this is what it looks like "P171;P172".

  if (ModelState.IsValid)
    {
        hiddenIDnumber= hiddenIDnumber.Trim();
        List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();

        foreach (string str in listStrLineElements)

The problem is, when I split my hiddenIDnumber, even if I have two numbers, I get a count of 3 and "" is returned (which I believe is an empty space). When I use a breakpoint i get "P171","P172" AND "". This is causing my program to fail because of my FK constraints.

Is there a way to "overcome this and somehow "trim" the space out?

Upvotes: 1

Views: 3082

Answers (5)

Andrew
Andrew

Reputation: 1596

You will end up with the number of ;s plus one when you split. Since your comment mentions you have 2 ;s, you will get 3 in your list: before the first semicolon, between the first and the second, and after the second. You are not getting an empty space, you are getting a string.Empty because you have nothing after the last ;

if (ModelState.IsValid)
{
    hiddenIDnumber= hiddenIDnumber.Trim(";");
    List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();

    foreach (string str in listStrLineElements)

This way you get rid of the ; at the end before you split, and you don't get an empty string back.

Upvotes: 0

Adrian
Adrian

Reputation: 131

You can try:

IList<string> listStrLineElements = hiddenIDnumber.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

I prefer this over new [] { ';' } for readability, and return it to an interface (IList<string>).

Upvotes: 0

DavidG
DavidG

Reputation: 118937

Use another overload of string.Split whih allows you to ignore empty entries. For example:

List<string> listStrLineElements = hiddenIDnumber
    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
    .ToList();

Upvotes: 7

Richard
Richard

Reputation: 21

I would say that one way to do this would be to use String Split Options. With String.Split there is an overload that takes two arguments, i.e. it would be like

myString.Split(new [] {';'}, StringSplitOptions.RemoveEmptyEntries);

This should prevent any entries in your array that would only be an empty string.

Upvotes: 2

NineBerry
NineBerry

Reputation: 28499

var listStrLineElements = hiddenIDnumber.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);

Use the parameter StringSplitOptions.RemoveEmptyEntries to automatically remove empty entries from the result list.

Upvotes: 0

Related Questions