2

I have an array which I split on basis of comma "," but there is a last entry as empty because I am concatenating it in jquery. I used

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

but it removes all the empty entries from an array e.g. if my array is

 "1"," ","2","3"," " 

it returns 1,2,3. But I want it to remove only the last one from it e.g. return 1," ",2,3. Is it possible to do it without substracting 1 from the array?

4 Answers 4

4

You can use TrimEnd method to remove whitespaces from end on the String instance before calling Split:

string input = "1,2,3, ,4, , ";
input.TrimEnd()
   .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

Output Array:

["1"," ","2","3"," ","4"," "] 

See DEMO Fiddle here

Sign up to request clarification or add additional context in comments.

2 Comments

to verify it: Console.Write(item+"I"); we can see It still consider a space as an element
Actually its result is ["1","2","3"," ","4"," "]
2

First, use TrimEnd to prevent the aforementioned edge case and then split:

input.TrimEnd(' ',',').Split(new char[] {','}, StringSplitOptions.None);

1 Comment

This looks like the best way. Except that it should be StringSplitOptions.None since he want to return 1," ",2,3
2

If we want to skip all whitespace only items starting from end let's Reverse, then SkipWhile (as usual) the items we want to get rid of and, finally, Reverse back again:

  string input = "1,2,3, ,4, , ";

  ["1", "2", "3", " ", "4"]
  string[] array = input
    .Split(',') // it seems we don't want to remove empty in the middle
    .Reverse()
    .SkipWhile(item => item.All(c => char.IsWhiteSpace(c)))
    .Reverse()
    .ToArray();

If you want all items except last one:

  // All items
  string[] array = input
    .Split(',');

  // Removing the last item: ["1", "2", "3", " ", "4", " "]
  Array.Resize(ref array, array.Length - 1);

Comments

0

You can also try this Code to remove last element (if (Last_Element == " ")) of array.

class Program
{
    static void Main(string[] args)
    {
         // Simple Array:
         string[] array = new string[] { "1" , "2" , "3" , "4" , "5" , " "};

         // Converting Array into a List. (Because we don't have any remove method for array.)
         var arrayList = array.ToList();

         // Retrieving last element.
         string _lastSpace = arrayList.Last();

         // Confirmation: Last Element is space or not.
         if(_lastSpace == " ")
             arrayList.RemoveAt(arrayList.LastIndexOf(" "));

         // Converting the list without having last Element with space to "array"
         array = arrayList.ToArray();

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.