Anselmo GPP
Anselmo GPP

Reputation: 451

Modifying strings in an Array of strings

I have an array of strings and I would like to modify its elements at will. This is the code:

char pieces[9][4] = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };
pieces[2] = { " x " };

As I know, the elements in pieces[] are string literal, so they can't be changed (I'm not sure why this is like this). Maybe it could be solved using std::string or vectors. However, I would like to know if this kind of operation, or very similar operations, can be done using an array of strings. Can be done something like this using just an array of strings?

Upvotes: 0

Views: 95

Answers (5)

Anselmo GPP
Anselmo GPP

Reputation: 451

Just to sumarize the different solutions given by different users, the options are:

  • Modify one char element at a time. Example: pieces[2][1] = 'x'

  • Use strcpy(). Example: strcpy(pieces[2]," x ")

  • Another types: std::array, std::string, std::vector

Upvotes: 0

eneski
eneski

Reputation: 1655

Firstly, using curly brackets like pieces[2] = { " x " }; is the way of initialization, so you can't do that.

Secondly, pieces[2] is an char array, so it is not modifiable l-value.

You can either change its content element by element or by using strcpy() function.

Upvotes: 1

scohe001
scohe001

Reputation: 15446

In your specific situation, it looks like you always have some character surrounded by spaces, so you could simply do pieces[2][1] = 'x'; to modify that one element. However...

You are correct to assume this can be made easier with std::string and std::vector, but since we already know the size, an std::array will probably be better here:

std::array<std::string, 9> pieces = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };
pieces[2] = " x ";

You may notice that the subscript operator still works on std::array's. This means that even if you switch to std::array's, you probably won't even have to change too much in your other code (just the parts dealing with c-strings to be dealing with std::strings)

Upvotes: 4

cse
cse

Reputation: 4104

You can use strcpy();

See following example code. See working code here:

int main(void) 
{
    char pieces[9][4] = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };

    printf("At point 1: %s\n",pieces[2]);
    strcpy(pieces[2]," x ");
    printf("At point 2: %s",pieces[2]);
    return 0;
}

Output:

At point 1:  a 
At point 2:  x 

Upvotes: 3

Ryan Stout
Ryan Stout

Reputation: 1028

Does

pieces[2][0] = ' ';
pieces[2][1] = 'x';
pieces[2][2] = ' ';
pieces[2][3] = '\0';

do what you want?

Upvotes: 1

Related Questions