possibe to delete string from string[] ?

  • Thread starter Thread starter Beemer Biker
  • Start date Start date
B

Beemer Biker

I wanted to truncate a string array by removing the last item.
"strResult.length = n-1" does not work as the length is read only. I tried
strResult[n] = null and just got a null. Also tried strResult[n].Remove(0)
and all it did was delete characters, not remove the string. I can create a
string the correct size using "new string [n-1]" and then copy but it seems
there should be an easier way. I cant seem to make VS 2008 get me good help
on "string[]" It is not the same as StringBuilder and is just an array of
strings is it not?

...TIA..
 
I can create a string the correct size using "new string [n-1]" and then
copy but it seems there should be an easier way.

Nope. When working with a plain old array, that's all you get. You ought to
consider using List<string> instead. It still does that under the covers,
but up front you get nice things like Remove().
 
By design arrays are of fixed side. I would suggest using a generic List of
strings: List<string>, which you can manipulate as you wish. Removing the
last item can be done by calling "lst.RemoveAt(lst.Count - 1)".
 
Beemer said:
I wanted to truncate a string array by removing the last item.
"strResult.length = n-1" does not work as the length is read only. I
tried strResult[n] = null and just got a null. Also tried
strResult[n].Remove(0) and all it did was delete characters, not remove
the string. I can create a string the correct size using "new string
[n-1]" and then copy but it seems there should be an easier way. I cant
seem to make VS 2008 get me good help on "string[]" It is not the same
as StringBuilder and is just an array of strings is it not?

Other have suggested List<string>. That is perfect if you
will always remove the last item. If you frequently want to remove
items in the middle, then LinkedList<string> may have some advantages.

Arne
 
MC said:
Arne Vajhøj said:
Beemer said:
I wanted to truncate a string array by removing the last item.
"strResult.length = n-1" does not work as the length is read only. I
tried strResult[n] = null and just got a null. Also tried
strResult[n].Remove(0) and all it did was delete characters, not remove
the string. I can create a string the correct size using "new string
[n-1]" and then copy but it seems there should be an easier way. I cant
seem to make VS 2008 get me good help on "string[]" It is not the same
as StringBuilder and is just an array of strings is it not?
Other have suggested List<string>. That is perfect if you
will always remove the last item. If you frequently want to remove
items in the middle, then LinkedList<string> may have some advantages.

What is the difference?

List is great for adding and removing at the end and to get
elements by index.

LinkedList is great for inserting and removing in the middle.

Because they use an array and linked list as backing storage
respectively.

Arne
 
Back
Top