Back
Close

How to play with strings in C

Donotalo
2585.1K views
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:

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io