Lesson 7: Strings – Turning Characters Into Words (And Making Sense of Them)
Welcome back, fearless code explorer! 👋
Today, we’re entering the world of strings — because, let’s be honest, numbers are great, but sometimes you need words! Whether it’s printing a name, reading a sentence, or making a program feel more human, strings are your go-to tool.
So grab your cup of coffee (or tea, I won’t judge), and let’s figure out how to manipulate characters like a pro.
What is a String?
A string in C is essentially an array of characters. That’s right, those magical arrays are back! But this time, instead of storing numbers, we’re storing characters that, when combined, form words, sentences, or even paragraphs.
In C, strings are arrays of char
type, and they end with a special character called the null terminator (\0
), which tells the program where the string ends.
Here’s how you declare a string:
char name[10] = "Alice";
Explanation: We’ve declared a character array name
that can store up to 10 characters. The string "Alice"
is stored in this array, and C automatically adds the null terminator at the end.
Printing Strings
Printing strings is as simple as using printf
with the %s
format specifier. Let’s try it:
#include <stdio.h>
int main() {
char name[10] = "Alice";
printf("Hello, %s!\n", name);
return 0;
}
Explanation: We used %s
to print the string stored in the name
array. Easy, right?
String Input
Getting input from the user is where things get a little tricky in C. You can use scanf
, but it comes with risks (like overflowing the buffer if the user enters too much text). A safer option is fgets
, which lets you limit how many characters you want to read.
Here’s how you can safely take a string as input:
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Safer than scanf
printf("Hello, %s", name);
return 0;
}
Explanation: fgets
reads up to 49 characters (leaving space for the null terminator) from the user’s input and stores it in the name
array. Notice how we’re using sizeof(name)
to ensure we don’t overflow the array.
String Manipulation
Now let’s talk about manipulating strings. Since strings are just arrays of characters, you can access and modify individual characters using their index, just like with any other array.
Here’s an example of changing the first letter of a string:
#include <stdio.h>
int main() {
char name[] = "Bob";
printf("Original name: %s\n", name);
name[0] = 'R'; // Change 'B' to 'R'
printf("Modified name: %s\n", name);
return 0;
}
Explanation: We accessed the first character of the string (index 0
) and changed it from 'B'
to 'R'
, transforming "Bob"
into "Rob"
.
String Functions
C provides a set of functions to make working with strings easier. Some of the most commonly used are:
strlen
– Get the length of a string (excluding the null terminator).strcpy
– Copy one string into another.strcmp
– Compare two strings to see if they are the same.strcat
– Concatenate (join) two strings.
Let’s try them out:
#include <stdio.h>
#include <string.h> // Needed for string functions
int main() {
char first[20] = "Hello";
char second[20] = "World";
printf("Length of first: %lu\n", strlen(first)); // %lu for size_t type
strcat(first, second); // Concatenates second to first
printf("After concatenation: %s\n", first);
strcpy(second, "Everyone");
printf("New second: %s\n", second);
if (strcmp(first, second) == 0) {
printf("The strings are the same.\n");
} else {
printf("The strings are different.\n");
}
return 0;
}
Explanation:
strlen(first)
returns the length of the string"Hello"
.strcat(first, second)
joins"World"
to the end of"Hello"
, making it"HelloWorld"
.strcpy(second, "Everyone")
copies"Everyone"
intosecond
, replacing"World"
.strcmp(first, second)
compares the strings and lets us know if they are the same or different.
Strings and Pointers
In C, you can also work with strings using pointers. Here’s a quick example:
#include <stdio.h>
int main() {
char *name = "Alice";
printf("Hello, %s!\n", name);
return 0;
}
Explanation: Here, name
is a pointer to the string "Alice"
. This is a more memory-efficient way to handle strings, but it requires careful management to avoid overwriting memory unintentionally.
Homework Challenge: Favorite Movie Survey
Create a program that:
- Asks the user to input their favorite movie title.
- Prints a message that includes the movie title.
- Uses
strlen
to print how many characters are in the movie title.
Final Thoughts
Congratulations! You’ve now mastered the basics of working with strings in C. Strings are incredibly useful for handling text, and they’re everywhere in programming. In Lesson 8, we’ll explore functions in more depth, building on what we’ve learned so far. See you there! 🎉✨
See also
- Lesson 6: Arrays – Organizing Your Data Like a Pro
- Lesson 5: Functions – Breaking Down the Chaos (And Avoiding Code Repetition!)
- Lesson 4: Control Structures – Making Decisions (And Telling Your Program What to Do!)
- Lesson 3: Arithmetic Operations – Making Your Variables Work for You!
- Lesson 2: Variables – From Zeroes and Ones to Naming Your Data