Insert a element in String array
I have string containing n elements.
I want to insert a automatically incremented number to the first position.
E.g Data
66,45,34,23,39,83
64,46,332,73,39,33
54,76,32,23,96,42
I am spliting to string to array with split char ','
I want resultant array with a incremented number a first position
1,66,45,34,23,39,83
2,64,46,332,73,39,33
3,54,76,32,23,96,42
开发者_JAVA百科
Please suggest how can I do it.
Thanks
You can't with an array, you need to use a List<string>
instead.
For example:
List<string> words = new string[] { "Hello", "world" }.ToList();
words.Insert(0, "Well");
Linq has an easy way to accomplish your "mission":
First add the correct namespace:
using System.Linq;
And then:
// Translate your splitted string (array) in a list:
var myList = myString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
// Where insertPosition is the position you want to insert in:
myList.Insert(insertingPosition, insertedString);
// Back to array:
string[] myArray = myList.ToArray<string>();
Hope this helps...
You cannot insert anything to Array. Use List<T>
instead.
You have to use something like an ArrayList instead, which has an ArrayList.Insert() method.
ArrayList myAL = new ArrayList();
myAL.Insert( 0, "The" );
myAL.Insert( 1, "fox" );
myAL.Insert( 2, "jumps" );
myAL.Insert( 3, "over" );
myAL.Insert( 4, "the" );
myAL.Insert( 5, "dog" );
well what if you have the list like the following
string a="66,45,34,23,39,83";
string b="64,46,332,73,39,33";
string c="54,76,32,23,96,42";
before splitting a,b,c...
string[] s=new string[]{a,b,c};
for(int i=0; i<s.length;i++){
s[i]=(i+1)+s[i];
}
now split each string in s
you will have a list like
1,66,45,34,23,39,83 2,64,46,332,73,39,33 3,54,76,32,23,96,42
I am not sure if I have understood your problem or not. :|
I know you want a C# answer (and there are good answers here already in that language), but I'm learning F# and took this on in that language as a learning exercise.
So, assuming you want an array of strings back and are willing to use F#...
let aStructuredStringArray = [|"66,45,34,23,39,83"
"64,46,332,73,39,33"
"54,76,32,23,96,42"|]
let insertRowCountAsString (structuredStringArray: string array) =
[| for i in [0 .. structuredStringArray.Length-1]
do yield String.concat "" [ i.ToString(); ","; structuredStringArray.[i]]
|]
printfn "insertRowCountAsString=%A" (insertRowCountAsString aStructuredStringArray)
C# arrays cannot be resized. This means that you can't insert items.
You have two options:
- Use a
List<T>
instead. - Create a new array, with one extra item in, copy the contents of the old one across and so on.
Option 1 is invariably to be preferred.
There is Array.Resize(T)
. On the face of it this contradicts what I state above. However, the documentation for this method states:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
精彩评论