- Strings
- Strings are arrays of char whose last element is a null character '\0' with an ASCII value of 0. C has no native string data type, so strings must always be treated as character arrays.
Strings:
- Are enclosed in double quotes "string"
- Are terminated by a null character '\0'
- Must be manipulated as arrays of characters (treated element by element)
- May be initialized with a string literal
Creating a String Character Array
Strings are created like any other array of char:
char arrayName [length];
- length must be one larger than the length of the string to accommodate the terminating null character '\0'
- A char array with n elements holds strings with n-1 char
Example
How to Initialize a String at Declaration
Character arrays may be initialized with string literals:
char arrayName [] = "Microchip";
- Array size is not required
- Size automatically determined by length of string
- NULL character '\0' is automatically appended
Example
How to Initialize a String in Code
arrayName [0] = char1;
arrayName [1] = char2;
.
.
.
arrayName [n] = '\0';
- Null character '\0' must be appended manually.
Example
Comparing Strings
- Strings may not be compared as ordinary variables: we cannot do if( str1 == str2) the way we do if (x == y).
- To compare two strings, it is necessary to compare them character by character.
- C provides string comparison/manipulation functions as part of the standard C library.
- When using strcmp() to compare two strings, it returns 0 (FALSE) when they match – so its logic must be inverted when used as a conditional expression.
Example
Code Example
1. Create a character array and initialize it with the string literal "Hello".
2. Test to see if the string contained in the character array str matches the string literal "Hello". Note that strcmp() may compare two array variables or compare with a string literal as we did here. E.g. strcmp(str1, str2) or strcmp(str1, "This string"). The strcmp() function will return 0 if the strings match, it will return < 0 if the first string is less than the second and it will return > 0 if the first string is greater than the second string.
3. If the strings match, print out the message including the value of str.