How to play with strings in C

Donotalo
2610.6K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: String Split

If a C string is a one dimensional character array then what's an array of C string looks like? It's a two dimensional character array!

Here is how an array of C string can be initialized:

#define NUMBER_OF_STRING 4
#define MAX_STRING_SIZE 40

char arr[NUMBER_OF_STRING][MAX_STRING_SIZE] =
{ "array of c string",
  "is fun to use",
  "make sure to properly",
  "tell the array size"
};

Since all but the highest dimension can be omitted from an array declaration, the above declaration can be reduced to:

#define MAX_STRING_SIZE 40

char arr[][MAX_STRING_SIZE] =
{ "array of c string",
  "is fun to use",
  "make sure to properly",
  "tell the array size"
};

But it is a good practice to specify size of both dimensions.

Now each arr[x] is a C string and each arr[x][y] is a character. You can use any function on arr[x] that works on string!

Following example prints all strings in a string array with their lengths.

#define NUMBER_OF_STRING 4
#define MAX_STRING_SIZE 40

char arr[NUMBER_OF_STRING][MAX_STRING_SIZE] =
{ "array of c string",
  "is fun to use",
  "make sure to properly",
  "tell the array size"
};

for (int i = 0; i < NUMBER_OF_STRING; i++)
{
    printf("'%s' has length %d\n", arr[i], strlen(arr[i]));
}

Following example reverses all strings in a string array:

Following example concatenates all strings in a string array with space between them into a single string:

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content