UPI Study › Courses › C++ Programming › Free lessons › Lesson 7.2 Free with a free account
Utilities for Text
C++ Programming · Chapter 7: Text and Applied CollectionsSection 7.2 · lesson 44 of 84video coming soon
← Characters and Text in C++Next lesson: Assembling and Editing String Content →
In this lesson
Pre-built tools for measuring, searching and slicing.
- Measure a string, and reach one character safely
- Search with find, and test the result against npos
- Extract with substr, and compare strings
- Classify characters; see why strcpy overflows
Transcript
Everything said in the video, section by section (1,605 words). Read along, or search it.
Lesson Overview
Inspecting Text Without Changing It
Almost everything you'll ever want to ask about a piece of text has been asked before, and the standard library has an answer ready. This lesson covers the operations that inspect text without changing it: measuring it, reaching into it, searching it, cutting pieces from it, comparing it, and classifying its characters. It also covers the older toolkit for plain arrays, and the specific danger that comes with it.
Two Toolkits
Strings Versus C-Strings
C++ carries two ways of holding text, and each comes with its own utilities. A std::string knows its own length, manages its own storage, and offers its operations as things you ask of the string itself, after a dot. A C-string is a plain array ending in a marker. It knows nothing about itself, so its operations are separate functions that take the array as an argument. Nearly all new code should use the first. The second is covered because existing code uses it, and because the way it fails is worth understanding.
Length and Size
Two Names, One Measurement
Take the string Bhubaneswar. Its length is 11. Its size is also 11: the same function under a second name. And empty is false. Length reads better for text. Size is the name every other container in the library uses, so generic code uses that one. Pick either, and be consistent. Empty answers whether the length is zero. Prefer it over comparing the length with zero yourself: it states the intention, and it's never slower.
Element Access
Checked At Versus Brackets
Characters are numbered from zero, exactly as array elements are. There are two ways to reach one, and they differ in a single respect that matters a great deal. Square brackets behave exactly like array subscripting. They compute a position and read there, with nothing verifying the index is sensible. At checks first. If the index is out of range, it throws an exception, which, if nothing catches it, stops the program with a message. Run it. The first line prints Go. Then the program stops on the bad index, instead of quietly reading memory that isn't the string's. Some compilers name the index and the real length too. So use at whenever an index comes from somewhere you don't fully control: arithmetic, a search result, or input. Use brackets when the index demonstrably can't be out of range, like a loop counter bounded by the string's own length.
Searching
Find, Rfind, and Find First Of
Three search operations cover most needs. All three answer with a position, rather than with true or false. Take the string, the cat sat on the mat. Find the gives 0, the first occurrence. R find gives 15, the last occurrence, still counted from the left. Find first of the vowels gives 2, the position of whichever vowel appears earliest. Find the, starting from 5, gives 15: the first occurrence at or after position 5. Used repeatedly, that finds every occurrence. Notice the difference between find and find first of. Find, given a e i o u, looks for those five letters as a run, in that exact order. Find first of treats them as a set, and takes whichever appears first.
Not Found
Testing Results Against npos
A search that finds nothing can't return a position, so it returns a special value named npos. Printed, it looks alarming: a 20-digit number. That's the largest value a 64-bit unsigned type can hold. Positions are unsigned, so it's the one value that can never be a real answer: a safe marker for not found. Because npos is an enormous positive number, the test people reach for first doesn't work. Position at least zero is always true, like an unsigned countdown that never finishes. The one correct test is against the name itself. Equal to npos means not found. Not equal means found. And a successful search can legitimately return zero, when the match is at the very start. Any test that treats zero as failure is wrong for that case.
Cutting Pieces
Substr Takes a Start and Count
Substr produces a new string containing part of the original. The original isn't touched. It takes a starting position and, optionally, how many characters to take. On the date 2026-09-03: start at 0, take 4, gives 2026. Start at 5, take 2, gives 09. Start at 5 and take the rest, gives 09-03. The second argument is a count, not an end position. Substr 5, 2 takes two characters starting at 5, positions 5 and 6. It doesn't stop at position 2. And asking for more characters than remain isn't an error. You simply get what's there.
Comparison
Lexicographic Order by Character Code
Unlike arrays, strings compare exactly as you'd hope. The relational operators examine contents, not addresses, and equals-equals means what it says. The ordering is lexicographic. The two strings are walked together from the left, and the first position where they differ decides the result, by comparing those two characters. Apple against apricot: a, p, the same. Then p against r. P is 112 and r is 114, so apple comes first. Everything after that is never examined. If no difference is found before one string runs out, the shorter one comes first. That's why app comes before apple. And because every capital has a smaller code than every small letter, Zebra comes before apple. It's character-code order, not dictionary order, and not case-insensitive. Sorting names this way places every capitalized entry before every lowercase one. A correct answer to the question asked, and rarely the ordering a reader expects. The relational operators each answer one yes-or-no question. Compare answers all of them at once, by returning a number whose sign carries the result. Zero means equal. Negative means the first string comes before the second. Positive means it comes after. Only the sign is defined. Never test for minus 1 or 1 specifically; that's just what one implementation produced. Use compare where one call must distinguish three outcomes, such as inside sorting logic. Use the operators everywhere else, because they read better.
Character Functions
Classifying and Converting with cctype
The cctype header supplies small functions that answer questions about one character, and two that convert case. Is alpha asks whether it's a letter. Is digit, whether it's 0 to 9. Is space asks about whitespace: space, tab, or newline. Is upper and is lower ask for a capital or a small letter. Is alnum asks for a letter or a digit. And to upper and to lower convert a letter's case, leaving anything else alone. They work on single characters, so the usual pattern is a loop over a string.
Common Surprise
These Functions Use int, Not char
Two details about these functions surprise people, and both show up the moment you print a result. They take and return int, not char. So the is functions return a nonzero number for true, rather than true itself. Printing one shows a nonzero number; here it's 1. And to upper returns the code of the converted character, so printing it directly shows 75. Cast it to char to see K. Keep both details in mind whenever you print one of these results.
Worked Example
Casting to Unsigned Char
There's also a requirement that's easy to miss. The argument must be passed as an unsigned char. Plain char may be signed, so a character outside plain English can arrive as a negative number, which these functions don't accept. This loop casts each character first, then counts letters, digits and spaces. For MP04 AB 1234, it finds 4 letters, 6 digits, and 2 spaces.
C-String Basics
The Null Terminator and Strlen
A C-string is an array of characters with one extra rule: the text ends at the first character with the value zero, the null terminator. Nothing records the length. It's discovered by scanning for that marker. For Bhopal, strlen gives 6, the characters before the terminator. Sizeof gives 7, the storage, including the terminator. Forgetting that byte is the classic way to make a buffer exactly one character too small. Strcmp compares lexicographically, and returns a sign, exactly as compare does. For C-strings you must use it, because equals-equals on two character arrays compares addresses. The same trap as with arrays.
Danger
Strcpy and Buffer Overflow
Strcpy copies characters, terminator included, from a source to a destination. It's included because of what it demonstrates. It's never told how large the destination is. It copies until it meets the terminator, whatever lies beyond. Here, 25 characters plus a terminator go into an 8-byte buffer. The compiler warns. That's a buffer overflow, and its behavior is undefined. One build may abort on the spot. Another may print the full text, look like success, and corrupt something unrelated, to crash much later. It's behind a large share of the serious security failures of the last several decades. The compiler caught this one because the length was visible in the source. It can't when text arrives while the program runs, which is precisely the dangerous case. So the answer isn't care. It's std::string.
Side by Side
Same Jobs in Both Toolkits
Here are the same jobs in both toolkits. To find the length, a string knows it, while a C-string must be scanned every time. To test equality, use equals-equals on strings. C-strings need strcmp, because equals-equals on arrays is silently wrong. Ordering follows the same lexicographic rule in both. Copying a string resizes it to fit, while strcpy can overrun the array. And to reach one character safely, strings have at, and arrays have no checked equivalent at all.
Quick Check
What Does Substr 2, 4 Give
Quick check. Take the same date, 2026-09-03. What does substr 2, 4 give? Pause and think. It gives 26-0: four characters, starting at position 2. If the 4 were an end position, you'd get only 26.
Key Takeaways
Summary of Text Utilities
To summarize. Length and size are the same operation; prefer empty to test for zero. At checks the index, and brackets don't. Searches return a position, or npos, so test only against npos. Substr takes a start and a count, not an end. Comparison is by character code. And avoid strcpy.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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 Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming 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 Utilities for Text
What is the difference between at() and square brackets for reaching one character in a C++ string?
How do I test whether string find() found a match in C++?
What do the two arguments of substr mean in C++?
Why is strcpy unsafe in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →