UPI Study › Courses › Programming in C › Free lessons › Lesson 7.6 Free with a free account
Standard String Library Functions
Programming in C · Chapter 7: Arrays, Strings, Input Validation, and Formatted OutputSection 7.6 · lesson 45 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Input Validation and Formatted Output in C →← String Representation in CNext lesson: Input Validation and Formatted Output in C →
In this lesson
Measuring, copying, joining, and comparing strings with string.h and ctype.h.
- Compare what strlen and sizeof report for a string
- Copy and join strings with strcpy and strcat, and explain their overflow risk
- Test two strings for equality with strcmp instead of ==
- Use snprintf or strncpy plus a null terminator to copy safely
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (890 words). Read along, or search it.
Opening Question
Everyday Jobs With Names at the Desk
At the arcade desk, Priya works with names all day. She counts letters, copies a name onto a badge, checks whether two names match, and glues first and last names together. Writing a loop for each job would be tiring. C already ships the tools, in a toolbox called string dot h. You only need to know what each tool does, and one big danger that comes with them.
String Length
Strlen Counts Letters, Sizeof Counts Room
Every string function here lives in the header string dot h, so include it at the top. The first tool is strlen, string length. It counts the letters from the start up to, but not including, the marker. Run it. Strlen says nine, and sizeof says twenty. Strlen asks how long the text is right now. Sizeof asks how much room the array has. Both matter: the first tells you what's stored, and the second tells you what's safe. A string of n letters always needs n plus one boxes.
Common Mistake
Arrays Cannot Be Assigned With Equals
With a number, you can write score equals fifty any time. With a string array, you can't assign the whole array with equals. Try it: tag equals Sam. Build it, and clang refuses: array type char thirty is not assignable.
Copy and Glue
Strcpy and Strcat Trust the Destination
Instead, copy the letters with strcpy, destination first, then source. It copies every letter, and the marker too. To glue text onto the end, use strcat, string concatenate. It finds the marker, writes the new letters over it, and puts a fresh marker at the end. Run it. Player colon Priya, thirteen letters. Then strcpy replaces the text with Sam. Both tools trust you completely: the destination must be big enough for the result.
Common Mistake
Double Equals Compares Addresses
How do you check whether two names match? The obvious double equals doesn't compare letters. It asks whether the two arrays live at the same place in memory, which two separate arrays never do. Clang even warns: array comparison always evaluates to false. Run it anyway, and two names that are both Sam come out different.
Comparing Strings
Strcmp Returns Negative, Zero, or Positive
The right tool is strcmp, string compare. It walks both strings together, and stops at the first box where they differ, or at the markers. It returns a negative number when the first string comes first in alphabetical order, zero when they're exactly the same, and a positive number when the first comes later. The exact negative or positive number can differ between systems, so test only the sign. Run it. Apple before banana, negative. Apple and apple, zero. Pear after banana, positive. And Zebra comes before apple! Strcmp compares letter numbers, and every capital has a smaller number than every small letter. Z is ninety, a is ninety-seven.
Quick Check
Zero Means the Names Match
Quick check. The player typed Sam, and this test uses strcmp to decide if it matches Sam. What does the program print? Pause and predict. No match, though the names are the same! Strcmp returns zero when they match, and zero counts as false, so the else branch runs. Write strcmp equals equals zero, and the code says what you mean.
Buffer Overflow
Strcpy Never Checks the Size
Now the big danger. An array has a fixed size, but strcpy never checks it. It keeps copying until it has copied the source's marker. Copy fifteen letters into an eight-box array: eight letters fit. The other seven, and the marker, land in memory that the array doesn't own. That's a buffer overflow, one of the most famous causes of crashes and security holes in C. It's undefined behavior, so we won't run one.
Safe Copies
Snprintf, or Strncpy Plus a Marker
Instead, use a copy that knows the size. Snprintf writes at most size boxes, and always ends with a marker. Strncpy copies at most n letters. But if the source is that long, it adds no marker, so you add one yourself. The size travels in as a separate number, because inside a function sizeof can't see the array's real size. Sam types StarlightArcade, fifteen letters. Both tools keep seven, S T A R L I G, plus the marker, and nothing spills out.
Character Tools
Testing and Changing Single Letters
One more toolbox, ctype dot h, works on single letters. Isdigit says whether a character is a digit, and isalpha whether it's a letter. Toupper gives the capital version. Pass each one the letter with unsigned char in front, to keep them safe. Put them in a loop that stops at the marker, and you can check or change every letter. Run it: A B 1 2 X, three letters and two digits.
Quick Check
Gluing Changes Text, Not Room
Quick check. A twenty-box tag starts as Star, and strcat glues light onto it. What do strlen and sizeof print? Pause and predict. Nine, then twenty. Starlight has nine letters, and strlen never counts the marker that strcat moved to the end. Sizeof still says twenty: gluing changes the text, not the array's room.
Story Resolved
A Short but Safe Badge
Back at the desk, Priya's badge printer had an eight-box name array. Test it with the longest name you can think of, she told Sam. He typed StarlightArcade. With her safe copy, the badge showed Starlig, and the printer kept running. Short, but safe, Sam said. Priya made a note to widen the array to twenty boxes.
Key Takeaways
The String Toolbox at a Glance
To recap. Strlen counts letters before the marker; sizeof counts the array's boxes. Strcpy and strcat copy and glue, destination first, and never check the size. Strcmp returns zero for a match, so test for equals equals zero. And for safe copies, use snprintf, or strncpy plus a marker.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Standard String Library Functions
What is the difference between strlen and sizeof for a C string?
How do you compare two strings in C?
How do you copy a string into a char array in C without overflowing it?
What do isdigit, isalpha, and toupper do in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →