C Programming Strings
Last modified by Microchip on 2023/11/09 09:06
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
1 char str1[10]; //Holds 9 characters plus '\0'
2
3 char str2[6]; //Holds 5 characters plus '\0'
2
3 char str2[6]; //Holds 5 characters plus '\0'
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 the length of string
- NULL character '\0' is automatically appended
Example
1 char str1[] = "Microchip"; //10 chars "Microchip\0"
2
3 char str2[6] = "Hello"; //6 chars "Hello\0"
4
5 //Alternative string declaration – size required
6 char str3[4] = {'P', 'I', 'C', '\0'};
2
3 char str2[6] = "Hello"; //6 chars "Hello\0"
4
5 //Alternative string declaration – size required
6 char str3[4] = {'P', 'I', 'C', '\0'};
How to Initialize a String in Code
arrayName [0] = char1;
arrayName [1] = char2;
.
.
.
arrayName [n] = '\0';
arrayName [1] = char2;
.
.
.
arrayName [n] = '\0';
- Null character '\0' must be appended manually.
Example
1 str[0] = 'H';
2 str[1] = 'e';
3 str[2] = 'l';
4 str[3] = 'l';
5 str[4] = 'o';
6 str[5] = '\0';
2 str[1] = 'e';
3 str[2] = 'l';
4 str[3] = 'l';
5 str[4] = 'o';
6 str[5] = '\0';
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
1 char str[] = "Hello";
2
3 if (!strcmp( str, "Hello"))
4 printf("The string is \"%s\".\n", str);
2
3 if (!strcmp( str, "Hello"))
4 printf("The string is \"%s\".\n", str);
Code Example
- Create a character array and initialize it with the string literal "Hello".
- 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, for example, 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.
- If the strings match, print out the message including the value of str.