Strings
Understanding Strings
What is a String?
In C programming, a String is simply a sequence of characters terminated by a special character called the Null Character (\0).
Essentially, a string is a 1-dimensional array of char. The null character tells the computer that the string has ended, which is why when you declare a string, you must ensure the array is large enough to hold the text plus that hidden extra character.
Syntax & Declaration
You can declare a string just like an array of characters. You can either specify the size manually or let C calculate it based on your initial text.
// Method 1: Using double quotes (Recommended)
char name[] = "SkillEco";
// Method 2: Character by character (Manual null character)
char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Practical Examples
Example 1: Printing a String
In C, the %s format specifier is used to read or print strings.
char message[] = "Welcome to C Programming"; // The computer prints until it hits the \0 character printf("Message: %s\n", message);
Example 2: Reading a String with scanf
char firstName[30]; printf("Enter your name: "); // Note: No & symbol is needed for strings in scanf scanf("%s", firstName); printf("Hello, %s!", firstName);
scanf("%s", ...), the input stops as soon as it hits a space. To read a full line with spaces (like "John Doe"), students should use the fgets() function instead!
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute