Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to insert element in an array.

For example

s[0]="Ram"
s[1]="Ravi"
s[2]="James"
s[3]="Jacob"
s[4]="Abdul"


Here I want to insert a new string before James.

The User Input should be James.

Automatically it should be inserted before James.
Posted

1 solution

First get the index of "James", add element at that position and increment all other indexes by 1.
C#
string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }

    result result;
}

reference : stackoverflow[^]

-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900