Strings in C are handled differently to standard Java as there is no set ‘String’ library. The following example will show how to make a simple string in C89 C.
char array[5] = "Test\0";
Note: Every string ends in a ‘Null Terminator’ which is shown by a ‘\0′. If you do not add this at the end of your string, C will actually add one for you. However, this acts as an element within the array so if you don’t add it, make sure that the fixed size is one more than the number of characters (including white spaces).
Outputting the elements of a string in one consecutive line requires ‘%s’ in the output.
printf("My array is: %s", array);
Output:
My array is: Test
When printing the array, there is no need to display particular elements (i.e. array[0]) as the variable ‘array’ itself is a pointer to the initial element within itself. Using %s then goes through the entire array.
White Spaces
When a string contains white space (e.g. spaces within a sentence) the output will not complete the string after the first instance of white space, as it classes it as a terminator. In order to do this, you will need to use regular expressions.
printf("My array is: %[A-Za-z ]", array);
The REGEX within the square brackets tells the program to output any letters from A-Z, a-z, and also white spaces.
Responses to “Array of Characters (Strings)”
Leave a Reply