Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to insert new elements into an existing array without overwriting the existing values.


C#
Console.Write("Enter the size of the array: ");
            string inputSize = Console.ReadLine();
            int stringSize;
            int.TryParse(inputSize, out stringSize);
 
            string[] stringArray=new string[stringSize];
            Console.WriteLine("Enter elements one by one\n");
            for (int index = 0; index < stringSize; index++)
            {
                stringArray[index] = Console.ReadLine();
            }
            Console.WriteLine("\n\nGiven Array\n");
            foreach (string strings in stringArray)
            {
                Console.WriteLine(strings);
            }
            Console.Write("\nEnter String: ");
          
            string input = Console.ReadLine();
            int TextIndex = Array.FindIndex(stringArray, m => m == input);
            
            Console.Write("\nRequired string index: {0}\n",TextIndex);
            int newSize=stringSize+1;
            Array.Resize(ref stringArray,newSize);
            
                                    
            int nIndex=TextIndex+1;
            while(nIndex>TextIndex)
            {
                if (nIndex < newSize)
                {
                    stringArray[TextIndex + 1] = stringArray[TextIndex];
                    nIndex++;
                }
 
               break;
            }
            Console.Write("\nEnter new string: ");
            stringArray[TextIndex] = Console.ReadLine();
 

 

 

 
            foreach(string newElements in stringArray)
            {
                Console.WriteLine(newElements);
            }
 

 

 

            Console.ReadLine();


SQL
If we give input as "one" "two" "three" "five" "six"

We should add "four" at runtime and add it in the array and array size size gets incremented.

Then the resulting array should be
"one" "two" "three" "four" "five" "six"
Posted
Updated 17-Feb-14 20:45pm
v2
Comments
Sergey Alexandrovich Kryukov 18-Feb-14 2:44am    
So annoying re-posts; this is spam.
—SA

1 solution

I already answered: How to insert elements into an existing string array[^].

With your behavior, you should rather leave this site. Helping you is totally useless.

—SA
 
Share this answer
 
Comments
KUMAR619 18-Feb-14 3:48am    
@SA Thanks I got the idea for the question

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