开发者

Splitting a string on a space and removing empty entries

I am splitting a string like this:

string[] elements = templine.Split
                      开发者_开发问答      (space, StringSplitOptions.RemoveEmptyEntries);

How can I get every element from templine except for [1] and assign it to string[] elements?


string[] elements = templine.Split(space).Where((s, i) => i != 1).ToArray();


Lots of crazy LINQ examples here. This should probably be more efficient, if that matters to you:

public static T[] SkipElement<T>(this T[] source, int index)
{
    // Leaving out null/bounds checking for brevity.
    T[] array = new T[source.Length - 1];
    Array.Copy(source, 0, array, 0, index);
    Array.Copy(source, index + 1, array, index, source.Length - index - 1);
    return array;
}

With this you could do:

string[] elements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries);
elements = elements.SkipElement(1);


List<String> elements = templine.Split
                                  (space, StringSplitOptions.RemoveEmptyEntries).
                                 ToList().
                                 RemoveAt(1);

If you feel the need to go back to an array...

string[] elements = templine.Split
                                  (space, StringSplitOptions.RemoveEmptyEntries).
                                 ToList().
                                 RemoveAt(1).
                                 ToArray();


If you can use Linq, you can probably do:

IEnumerable<string> elements = templine.Split(...).Take(1).Skip(1);


string[] elements = templine.Split
    (space, StringSplitOptions.RemoveEmptyEntries).Where(s => s != "[1]").ToArray();

if you mean you'd like to remove the second element

string[] elements = templine.Split
        (space, StringSplitOptions.RemoveEmptyEntries).Where((s, i) => i != 1).ToArray();


Using Linq, you can just do

IEnumerable<String> elements = 
  empline.Split(space, StringSplitOptions.RemoveEmptyEntries);
String[] result = 
 elements
 .Take(1)
 .Concat(elements
 .Skip(2))
 .ToArray();


After your code above:

elements = elements.Take(1).Concat(elements.Skip(2)).ToArray();

One thing I want to point out: Take and Skip will not throw errors even if the original elements is too short; they'll simply produce empty IEnumerables (which can be safely concatenated, and whose methods can be safely called).


Well, you could either ask your brother Jon

Or you could do something like this:

var elements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray();

This will give you an array that contains all but the first element. If you want the first, but not the second (as your question sort of suggests), you could do this:

var allElements = templine.Split(space, StringSplitOptions.RemoveEmptyEntries);
var someElements = allElements.Take(1).Concat(allElements.Skip(2)).ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜