Brandyn
Brandyn

Reputation: 3

Moving positions of strings in an array

int moveToEnd(string a[], int n, int pos);

Eliminate the item at position pos by copying all elements after it one place to the left. Put the item that was thus eliminated into the last position of the array. Return the original position of the item that was moved to the end. Here's an example:

string actors[5] = { "peter", "lois", "meg", "chris", "stewie" };
int j = moveToEnd(actors, 5, 1);  // returns 1
// actors now contains:  "peter"  "meg"  "chris"  "stewie"  "lois"

This is what I have so far:

int moveToEnd(string a[], int n, int pos)
{int i = 0;
int initial;
int initial2;
int initial3;
for (i=0; i<n; i++)
    {if (i<pos)
        initial=i-1;
    if (i>pos)
        initial2=i-1;
    else 
        pos + (n-pos);
}}

it is totally wrong but I am stuck trying to figure out how to move the position to the end and than shift all the other elements to the left.

Upvotes: 0

Views: 2466

Answers (2)

Petar Minchev
Petar Minchev

Reputation: 47373

string save = arr[pos];

for (int i = pos; i < n - 1; i++)
   arr[i] = arr[i + 1];

arr[n - 1] = save;

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76898

You don't need your second argument, as you can get the length of the array with a.length

The basic logic is this:

  • store the element at a[pos] in a temp String variable.
  • iterate from a[pos] to a[a.length - 2] storing a[pos + 1] to a[pos]
  • store the temp String to a[a.length - 1]

Upvotes: 1

Related Questions