UPI Study › Courses › Programming in C › Free lessons › Lesson 8.1 Free with a free account
Workshop: A Text Processing Utility
Programming in C · Chapter 8: Pointers, Pointer Arithmetic, and String Manipulation via PointersSection 8.1 · lesson 48 of 788 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: Pointer Fundamentals in C →← Workshop: Searching, Sorting, and Aggregating ArraysNext lesson: Pointer Fundamentals in C →
In this lesson
Reversing, tokenizing, and reformatting strings in C with plain indexes.
- Reverse a string in place with two indexes that move inward
- Split a line into words using a flag that tracks the edges of words
- Fix capitals with toupper and tolower and squeeze extra spaces in one pass
- Explain why a rebuilt string must end with a null terminator
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 (1,247 words). Read along, or search it.
Opening Question
Three Tools for Arcade Text
Every machine at the Starlight Arcade shows text: a name on the high-score board, words on the help screen, a title on the marquee. Somebody has to flip, cut and tidy that text before it appears. In this workshop, you'll build three small tools for it. One reverses a name, one splits a line into words, and one fixes capitals and spaces. Pointers start in eight point two, so every program here uses plain indexes, like name of i.
Reversing Plan
Two Indexes Swap Toward the Middle
Tool one. Priya wants a mirror mode for the high-score board, which shows names backward. A string is a row of chars ending in backslash zero. So reversing means swapping boxes inside that row: first with last, second with second to last, and so on. Two indexes do it. left starts at zero. right starts at the last letter: strlen minus one, which is eight for Starlight. Swap the two letters, move both indexes inward, and repeat while left is less than right. Nine letters need only four swaps. The middle letter, at index four, never moves. No second array is needed, so this is called reversing in place.
Worked Example
The Reverse Function in Code
Here's the function, reverse. Its parameter is char s with empty brackets, so it changes the caller's own array, as in seven point three. left starts at zero, and right at strlen of s, minus one. While left is less than right, the loop swaps the two boxes, then moves left up and right down. The helper, keep, is needed because two boxes can't trade values in one step. Without it, the first assignment would wipe out a letter before it was saved. Then main, at the bottom. It reads a line with fgets, cuts off the newline with strcspn, as in seven point seven, and calls reverse. Build it, run it, and type Starlight. Reversed: the same nine letters, backward, with the capital S at the end.
Quick Check
A Loop That Swaps Too Many Times
Quick check. Sam rewrites the loop test. Instead of left less than right, his loop keeps going while right is zero or more. Every letter gets a turn, he says. What does this program print? Pause and predict. It prints Pinball, unchanged. The loop now runs seven times, not three. The first three passes reverse the name, the middle letter swaps with itself, and the last three swap every pair straight back. That was Sam's real mistake: more swaps, he thought, means more reversed. The backward name needs the loop to stop at the halfway point, and left less than right is exactly that rule.
Tokenizing Plan
A Flag Marks the Edges of Words
Tool two. The help screen stores one long line of words, and Priya wants them shown one per row. Cutting a line into words is called tokenizing, and each piece is a token. The words may be split by one space, by several, or by a tab. The line may even start or end with spaces. The trick is a flag: a variable, zero or one, that remembers a single fact. Here, in word means: the last character was part of a word. A word begins when a letter arrives while the flag is zero. It ends when a space arrives while the flag is one. Follow the flag through go, two spaces, fast. The second space does nothing, because the flag is already zero.
Worked Example
Printing One Word per Row
Here's the program. isspace, from c type dot h, is true for a space, a tab, or a newline. The cast to unsigned char is the safe habit from seven point six. When a space arrives and in word is one, a word just ended: print a newline, and set the flag to zero. When a letter arrives and the flag is zero, a new word just began: count it, print its label, and set the flag to one. Every letter of a word is printed with putchar as it goes, so no second array is needed. And the last if handles a line that ends in the middle of a word. Priya runs it, and types extra spaces on purpose: two in front, three after gold, and two after token. Four words, one per row, and a total of four. The extra spaces vanished, because the flag only changes at the edges of a word.
Library Shortcut
Strtok Changes the String It Cuts
By the way, C's string library already has a word cutter, called strtok. But it writes backslash zero over the separators, so it changes the string it cuts. It also hands the words back as pointers, which start in eight point two. Building the cutter by hand shows exactly what it does.
Title Case Plan
Read and Write Indexes in One Pass
Tool three. A player typed a game title with wild capitals and extra spaces. The marquee wants one capital per word, and one space between words. Two jobs happen in one pass. First, the capitals. A flag called new word is one at the start, and after every space. A letter that arrives while it's one goes through toupper. Every other letter goes through tolower. Both come from c type dot h, and return the changed letter. Second, the spaces. Two indexes walk the same array. read looks at each typed character, and write marks the next spot of the cleaned text. A space is copied only when the last kept character wasn't a space. Here's h, i, two spaces, y, o. The second space is skipped. write never gets ahead of read, so the loop can safely write into the array it's reading.
Worked Example
Reformatting a Messy Game Title
Here's reformat. The for loop moves read along the string, while write moves only when a character is kept. A space is kept only if write is past zero and the last kept character isn't a space. Either way, new word becomes one. A letter after a space goes through toupper, and the flag drops to zero. Any other letter goes through tolower. After the loop, a space may be left at the end, so it's dropped. Then backslash zero, at write, marks where the new, shorter string stops. Main prints the text in square brackets, before and after, so you can see where it really starts and ends. Build it, run it, and type the messy title, spaces and all. Typed shows the spaces inside the brackets. Result: Starlight Racing Gp. One capital per word, and one space between words.
Quick Check
Why the Hyphen Keeps a Small T
Quick check. This short program keeps only the capitals rule. Here, only a space sets new word back to one. The title is laser-tag ARENA. What does it print? Pause and predict. It prints Laser-tag Arena, with a small t. The hyphen isn't a space, so new word stays zero, and the t after it goes through tolower like any other letter. ARENA comes after a space, so its A stays a capital, and the other four letters become small. A capital T would need the hyphen to start a word too. Try that change yourself: test for a hyphen as well as a space.
Edge Cases
Empty Lines and Only Spaces
Back to Priya and Sam. Sam tried the title tool with just the Enter key, and then with nothing but spaces. Both times, the result was an empty pair of brackets, and no crash. Good, said Priya. On an empty string, the loops never run.
Key Takeaways
Reverse, Tokenize, and Tidy
To recap. Reverse in place with two indexes that swap and move inward, while left is less than right. Tokenize with a flag that changes only at the edges of a word. Fix capitals with toupper and tolower, and squeeze spaces with a read index and a write index. And always end the new string with backslash zero.
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 Workshop: A Text Processing Utility
How do you reverse a string in place in C?
Why does my C string reverse loop leave the string unchanged?
How do you split a line into words in C without strtok?
How do you capitalize each word and remove extra spaces in a C string?
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 →