Workshop: A Text Processing Utility | Programming in C

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

← Workshop: Searching, Sorting, and Aggregating ArraysNext lesson: Pointer Fundamentals 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

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.

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 Workshop: A Text Processing Utility

How do you reverse a string in place in C?
Use two indexes that swap characters and move inward. Start left at 0 and right at strlen(s) - 1, swap s[left] and s[right] through a temporary char, then increase left and decrease right, repeating while left < right. A nine-letter word such as Starlight needs only four swaps, and its middle letter never moves. No second array is needed, which is why it is called reversing in place.
Why does my C string reverse loop leave the string unchanged?
The loop probably keeps swapping past the halfway point. If it runs until right drops below 0, the first half of the swaps reverses the string and the second half swaps every pair straight back. For Pinball, a loop that runs seven times instead of three prints Pinball unchanged. Use left < right as the loop condition so the swapping stops when the two indexes meet.
How do you split a line into words in C without strtok?
Walk the string with a flag, such as in_word, that remembers whether the previous character was part of a word. A word starts when a non-space character arrives while the flag is 0, and it ends when a space arrives while the flag is 1. Testing with isspace((unsigned char)c) from ctype.h treats spaces, tabs, and newlines alike, so extra spaces never create empty words.
How do you capitalize each word and remove extra spaces in a C string?
Make one pass over the array with a new-word flag and two indexes, read and write. A letter that arrives while the flag is 1 goes through toupper, other letters go through tolower, and a space sets the flag back to 1. Copy a space only when the last kept character is not a space, drop a trailing space, and write '\0' at the write index to end the shorter 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 →