Standard String Library Functions | Programming in C

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

← String Representation in CNext lesson: Input Validation and Formatted Output in C →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
strlen counts the characters before the null terminator, while sizeof counts the elements of the whole array. For char name[20] = "Starlight";, strlen(name) is 9 and sizeof name is 20. strlen tells you how long the text is right now, and sizeof tells you how much room the array has, which is what you need to know before copying or joining. strlen is declared in string.h.
How do you compare two strings in C?
Use strcmp from string.h, not ==. strcmp returns zero when the strings match, a negative number when the first comes earlier, and a positive number when it comes later, so test strcmp(a, b) == 0 for equality. Using == on two arrays compares their addresses, which differ for separate arrays. The comparison uses character codes, so "Zebra" comes before "apple": Z is 90 and a is 97.
How do you copy a string into a char array in C without overflowing it?
Use a copy that knows the destination's size, such as snprintf(dest, size, "%s", src), which writes at most size characters including the null terminator. Plain strcpy(dest, src) copies until the source's terminator and never checks the size, so a long source causes a buffer overflow. strncpy(dest, src, n) copies at most n characters but adds no terminator when the source is that long, so set one yourself.
What do isdigit, isalpha, and toupper do in C?
These functions from ctype.h work on single characters. isdigit(c) returns nonzero if c is a digit, isalpha(c) returns nonzero if c is a letter, and toupper(c) returns the capital version of a lowercase letter. Cast the argument to unsigned char, as in toupper((unsigned char)s[i]), to keep it safe. In a loop that stops at the null terminator, they check or change every character of a string.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →