简体   繁体   中英

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?

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

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

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, ie it would be like

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

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

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

使用参数StringSplitOptions.RemoveEmptyEntries可自动从结果列表中删除空条目。

You can try:

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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