A string is a particular format of array intended to store alphanumeric characters, i.e. text.
A classic example of a string is the first parameter of the printf()
function:
printf("Hello!");
In the above example, "Hello!"
is a string.
A string is a special case of character arrays, whose syntax they share. The following example declares :
char text[10];
In this section on strings, we will use the standard string.h
library which
contains the basic functions for string processing:
#include <string.h>
A string being an array, it is possible to initialize it at the declaration character by character :
char text[] = {'H','e','l','l','o','!','\0'};
Note by the way that the last character is '\0'
which is the first character of the ASCII table.
However, there is a more user-friendly way to initialize a string in the :
char text[] = "Hello!";
In C, double quotes mark the beginning and end of a string
(as in the printf()
function). Be careful not to confuse this syntax with
single quotes which are intended to specify a single character:
// Single character
char c = 'L';
// String
char text[] = "My text";
Here is an example of how to create a string:
// Declare and initialize a string
char text[] = "This is a string.";
// Display the string
printf ("%s\n", text);
// Display string and array sizes
printf ("Array size : %ld octets\n", sizeof(text));
printf ("String size : %ld caractères\n", strlen(text));
// Display the first cells of the array
printf ("text[0] = %c\n", text[0]);
printf ("text[1] = %c\n", text[1]);
printf ("text[2] = %c\n", text[2]);
printf ("text[3] = %c\n", text[3]);
Some comments about this example:
%s
is the format code that displays a string.sizeof()
returns the size of the array (which is not the same as the string).strlen()
returns the number of characters in the string.text[i]
allows to access the (i+1)th character of the string (or the (i+1)th cell of the array)Write a program that declares a string url
containing the text https://lucidar.me
.
Display:
String content : https://lucidar.me Array size : 19 octets String size : 18 caractères
We provide the following string declaration:
char str[] = "string";
Using a loop, iterate through the characters of the string one by one and display them as :
Use sizeof()
to determine the length of the array in the loop. Here is the expected output from this exercise:
str[0] = 's' = 115 = 0x73 str[1] = 't' = 116 = 0x74 str[2] = 'r' = 114 = 0x72 str[3] = 'i' = 105 = 0x69 str[4] = 'n' = 110 = 0x6E str[5] = 'g' = 103 = 0x67 str[6] = '' = 0 = 0x00
In C, a string ...
Which library contains the elementary functions for strings?
string.h
is a very popular library.
Try again...
What the following code displays:
char str[100] ="Cuckoo";
printf ("sizeof = %ld", sizeof(str));
sizeof()
.
Try again...
Qu'affiche le code suivant :
char str[100] ="Cuckoo";
printf ("strlen = %ld", strlen(str));
strlen()
.
Try again...