Insert a element in String array - c#

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
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.

Related

Store process output in array

I initiated an empty array - line.
string[] line = new string[] { };
I want to store every line that would be outputed in a cmd processing with the while loop below. This seems to work easily if I store the values in a string variable.
As shown below:
while (!proc.StandardOutput.EndOfStream)
{
line = proc.StandardOutput.ReadLine();
}
However, I'm not sure how to store the values as separate elements in the array. I've tried:
while (!proc.StandardOutput.EndOfStream)
{
for(a in line)
{
a = proc.StandardOutput.ReadLine();
}
}
But its not working.
This is probably a very basic question. But I'm still learning C#.
There are few solutions. One would be to use List<string> instead of string[]:
List<string> line = new List<string>();
And than add lines next way:
while (!proc.StandardOutput.EndOfStream)
{
line.Add(proc.StandardOutput.ReadLine());
}
An array works on the basis of indexing. So if you want to use an array you need to specify how long it has to be or in other words how many items it can contain:
// this array can store 100 items
string[] line = new string[100];
To access a certain position you need to use the [ ] operator and to move forward in the array you need an indexing variable of type int that you can increment each iteration
int indexer = 0;
while (!proc.StandardOutput.EndOfStream)
{
line[indexer] = proc.StandardOutput.ReadLine();
indexer ++; // increment
}
This way you need to know in advance how many items you want to deposit in your array.
Another way would be to use a flexible collection like List which can dynamically grow. Sidenote: The indexing works with the same [ ] operator, but the adding of items works via the Add method
If you want to know more have look at this overview of possible collection types

Displaying strings from Array without repeats

I working on a project in c# asp.net. I would like to randomly display a string from either an array or list, if certain conditions are met, I would like to display another random string that has not been displayed.
EX.
LIST<string> myString = new List<string> {"one", "two", "three", "four", "five"};
or
string[] myString = new[] {"one", "two", "three", "four", "five"};
void btnAnswer_Click(Object sender, EventArgs e)
{
string Next = myString[random.Next(myString.Length)];
if(my condition is met)
{
lbl.Text = Next;
}
}
I can randomly call a string from my list or array, but not sure how to store repeat results. I've tried using an algorithm that jumbles the array and then a counter for the index, but the counter (counter++) seems to add 1 once and then stops. I've tried using a list and removing the string I use, but it seems to repeat after all strings have been used.
If more code is needed I can provide, just need a point in the right direction.
One option is to display one of the random string and store it in a ViewState.
When you come next time again, check whether new random string is already there in ViewState or not. If it is there in ViewState then get another random string.
Couple of options:
Have an array or list which is a copy of the master array, and whenever you choose one, remove it from the array. Once the array is empty, refresh it from the master array.
Similar, just create your array, shuffle it, and start giving out strings by order. so array[0], next would be array[1], and so on, once you reach the end, shuffle and start again.
There are probably others as well :)
Edit:
If I understand correctly from the comments, you are talking about the option where the input is not unique to begin with. If that is the case, you can create your list with a simple linq query to get only unique values (using distinct), guaranteeing no duplicates.
Have a look at this question for an example.
You can copy the indices into a list, it will save memory while allow us to track all the remaining items:
var indices = Enumerable.Range(0,myString.Count).ToList();
//define some method to get next index
public int? NextIndex(){
if(indices.Count == 0) return null;
int i = random.Next(indices.Count);
int k = indices[i];
indices.RemoveAt(i);
return k;
}
if(my condition is met) {
int? nextIndex = NextIndex();
lbl.Text = nextIndex == null ? "" : myString[nextIndex.Value];
}
Note that the Text is set to empty if there won't be no more remaining string, however you can handle that case yourself in another way such as keep the text unchanged.
You could probably do that, but why not get a unique list of strings first?
var uniqueStrings = myString.Distinct().ToList();
Then as you select strings, do a .Remove() on the last randomly selected value from uniqueStrings.
You said that:
I've tried using a list and removing the string I use, but it seems to repeat after all strings have been used.
The problem here is using the same instance of random for your series after you've run out. If you re-instantiate random = new Random(), the variable is re-seeded and you will have totally different results from what was generated before.

2-Dimension array of List in C#?

I just want get a 2 dimension array of List in c#. In my thought, below should works but it didn't, the 1 dimension array of List works. I use Unity3D with Mono, however I think it's language related problem.
List<MyType>[,] twoDArrayofList;//don't work, it's type is List<MyType>
List<MyType>[] oneDArrayofList;//it's works, the type is List<MyType>
Anyone know what's wrong? Thank you.
What do you mean by "doesn't work"? What error are you getting?
I don't know about Mono (or Unity3D), but I just tried the following in a .NET project and got the results I expected:
List<string>[,] strings = new List<string>[2, 2];
strings[0, 0] = new List<string> { "One" };
strings[0, 1] = new List<string> { "Two" };
strings[1, 0] = new List<string> { "Three" };
strings[1, 1] = new List<string> { "Four" };
This is an older post, but it came up in my search for a similar answer. I found that creating a Dictionary instead of a List meets my needs. You can't iterate by index, but if you have a discrete list and you are iterating through the first string "Key", you can easily obtain the second string "Value".
Here is a stackoverflow post with examples:
What is the best way to iterate over a Dictionary in C#?

Removing one items from an array and moving the others backwards

I'll just go straight to the point. I want to move the items in an array in a uniform difference, let's say I have this.
string[] fruits = { "Banana", "Apple", "Watermelon", "Pear", "Mango" };
For example, let's say I want to remove the "Apple" so I'll do this.
fruits[1] = "";
Now all that left are:
{ "Banana", "", "Watermelon", "Pear", "Mango" }
How do I really remove the Apple part and get only:
{ "Banana", "Watermelon", "Pear", "Mango" }
Note that the index of all the items from "Watermelon" until the end of the array moves 1 backward. Any ideas?
The List class is the right one for you. It provides a method Remove which automatically moves the following elements backwards.
If you really want to use Arrays, you can use Linq to filter your list and convert to array:
string[] fruits = { "Banana", "Apple", "Watermelon", "Pear", "Mango" };
fruits = fruits.Where(f => f != "Apple").ToArray();
If you're not required to use an array, look at the List class. A list allows items to be added and removed.
Similar to Wouter's answer, if you want to remove by item index rather than item value, you could do:
fruits = fruits.Where((s, i) => i != 1).ToArray();
You can do something like this:
for( int i = 1; i + 1 < fruits.Length; i++ )
fruits[i] = fruits[i + 1];
fruits = System.Array.Resize( fruits, fruits.Length - 1 );
If you do not care about the order of the fruit in the array, a smarter way to do it is as follows:
fruits[1] = fruits[fruits.Length - 1];
fruits = System.Array.Resize( fruits, fruits.Length - 1 );
I think one of the most useful things a new programmer can do is study and understand the various collection types.
While I think the List option that others have mentioned is probably what you are looking for, it's worth looking at a LinkedList class if you are doing a lot of insertions and deletions and not a lot of looking up by index.
This is an example of how I used lists and arrays to remove an item from an array. Note I also show you how to use linq to search an array full of bad names to remove. Hope this helps someone.
public static void CheckBadNames(ref string[] parts)
{
string[] BadName = new string[] {"LIFE", "ESTATE" ,"(",")","-","*","AN","LIFETIME","INTREST","MARRIED",
"UNMARRIED","MARRIED/UNMARRIED","SINGLE","W/","/W","THE","ET",
"ALS","AS", "TENANT" };
List<string> list = new List<string>(BadName); //convert array to list
foreach(string part in list)
{
if (BadName.Any(s => part.ToUpper().Contains(s)))
{
list.Remove(part);
}
}
parts = list.ToArray(); // convert list back to array
}
As a beginner 3 years ago, I started making the software that I'm still working on today. I used an array for 'PartyMembers' of the game, and I'm basically today regretting it and having to spend a ton of time converting all this hard coded $#!t into a list.
Case in point, just use Lists if you can, arrays a nightmare in comparison.

Split and select specific elements

I have a comma separated string which specifies the indexes. Then I have one more comma separated string which has all the values.
EX:
string strIndexes = "5,6,8,15";
string strData = "ab*bc*dd*ff*aa*ss*ee*mm*jj*ii*waa*jo*us*ue*ed*ws*ra";
Is there a way to split the string strData and select only the elements which are at index 5, 6, 8 or 15. Or will I have to split the string first then loop through the array/list and then build one more array/list with the values at indexes defined by string strIndexes (i.e. 5, 6,7,15 in this example)
Thanks
It's reasonably simple:
var allValues = strData.Split('*')
var selected = strIndexes.Split(',')
.Select(x => int.Parse(x))
.Select(index => allValues[index]);
You can create a list from that (by calling selected.ToList()) or you can just iterate over it.
It depends a bit on the length of the string. If it is relatively short (and therefore any array from "Split" is small) then just use the simplest approach that works; Split on "*" and pick the elements you need. If it is significantly large, then maybe something like an iterator block to avoid having to create a large array (but then... since the string is already large maybe this isn't a huge overhead). LINQ isn't necessarily your best approach here...
string[] data = strData.Split('*');
string[] result = Array.ConvertAll(strIndexes.Split(','),
key => data[int.Parse(key)]);
which gives ["ss","ee","jj","ws"].
call Split(','); on the first string and you get an array of strings, that array you can access by index and the same you can do on the second array. No need to loop array lists.

Categories

Resources