0

If I have,

matrix1[4][4] = { 'a','b','c','d',
                  'e','f','g','h',
                  'i','j','k','l',
                  'm','n','o','p'}

string1[50] = "text" 

how do you go about adding a character from the matrix into the string? like if I wanted "g" added to "text" to make like string2 = textg

strcat doesn't take these parameters. Can I do something like making a separate char string2 = matrix1[2][3] and append that to string1? But what if i want more than 1 char like g and k to make textgk.

1
  • strncat(string1, matrix1[1][2], 1);strncat(string1, matrix1[2][2], 1); or char string2[50]; snprintf(string2, sizeof(string2), "%s%c%c", string1, matrix1[1][2], matrix1[2][2]);. note matrix1[1][2] : 'g' , matrix1[2][2] : 'k', matrix1[2][3] : 'l' Commented Apr 11, 2016 at 2:11

1 Answer 1

1

Assign it directly

text[4] = matrix [2][3];
text [5] = '\0';

Or you can do something like this.

 void appendChar(char * pString, char c)
{
    int len = strlen (pString);
    pString[len] = c;
    pString [len +1] = '\0';

}

appendChar (string1, matrix [2][3]);

Of course this function assumes pString points to a buffer big enough to hold the character to be appended.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.