Arrays With Text Processing, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 7.8 Free with a free account

Arrays With Text Processing

C++ Programming · Chapter 7: Text and Applied CollectionsSection 7.8 · lesson 50 of 84video coming soon

← Dynamic Vectors ChallengeNext lesson: Dividing Programs Into Callable Units →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Integrated exercises combining arrays and strings.

  • Turn a character into an array index
  • Walk two positions inward to test a palindrome
  • Split text into words without losing the last
  • Count words, test anagrams, encode, and sort

Transcript

Everything said in the video, section by section (1,541 words). Read along, or search it.

Opening Question

Combining Arrays, Strings, and Vectors

Every technique in the last two chapters has been practiced in isolation. Real problems don't arrive that way. Counting how often each letter appears needs an array and a string. Splitting a sentence into words needs a string and a vector. This lesson works through the combinations, as worked solutions to attempt first and then compare, and then asks you to do the same.

Core Idea

A Few Moves Behind Text Problems

Text problems look varied, and are built from a very small number of moves. Recognizing which move a problem needs is most of the work. To count each letter, use an array of 26 counters, indexed by the letter minus a. To compare a string with itself, use two indexes moving toward the middle. To split text, build one piece character by character, and at a separator, store the piece and start a new one. To transform every character, build a new string as you go. To count things you can't index, keep a vector of the distinct items beside a vector of counts. To put text in order, use a vector of strings.

Planning Checklist

Four Questions Before You Type

Ask four questions before you type. What is the collection, and what is the text? Naming both prevents the commonest confusion: treating a string as a collection, when the problem wanted a collection of strings. What does one pass accomplish? One character examined, one word completed, or one pair compared. What carries across passes? A running count, a partly built word, or a best so far. And what are the edge cases? Empty text, a single character, all separators, mixed case, and punctuation.

Worked Example

Character Frequency With a 26-Slot Array

First, character frequency: count how many times each letter appears in a line, ignoring case and non-letters. The move that makes this easy is turning a character into an index. Since a to z are contiguous, a character minus a gives 0 for a, 1 for b, and so on: exactly the range of a 26-element array. So d minus a is 3, and d's counter lives at index 3. Twenty-six separate counter variables would need 26 branches to choose between them. One array needs none. The loop checks each character is a letter, folds it to lower case, subtracts a, and adds one to that counter. The report loop turns the index back into a letter with char of a plus i. For Madhya Pradesh, a appears three times, d and h twice, and the rest once each.

Key Decisions

Zeros, Skipped Non-Letters, Reverse Arithmetic

Three decisions are worth noticing. The array is initialized to zeros, because counters that begin at whatever was in memory produce confident nonsense. Non-letters are skipped before the subtraction, so a space or a period never produces a negative index. And the report loop turns the index back into a letter with char of a plus i: the same arithmetic in reverse.

Worked Example

Palindrome Test With Two Inward Indexes

Next, a palindrome test: does a line read the same forward and backward, ignoring case, spaces, and punctuation? Reversing a copy and comparing would work. Two indexes walking inward is better: it stops at the first mismatch, and needs no second string. Left starts at the beginning, and right at the end. Each skips anything that isn't a letter. Then the two letters are compared, after folding case, and one mismatch settles it. Notice that the inner loops repeat the condition, left less than right. Without that, a line of nothing but punctuation would run one index past the other, and read outside the string. Guarding inside every loop that advances an index is a habit worth keeping. Run it: one, zero, one. The Panama sentence passes, Madhya fails, and the line of pure punctuation ends safely.

Worked Example

Splitting a Sentence Into Words

Now splitting a sentence into a vector of words. The pattern: accumulate characters into a partial word. When a separator arrives, store the word, and start again. Here, at each space, if the current word isn't empty, it's pushed into the vector and cleared. Any other character is added to the current word. The trap is the ending. The final word has no separator after it. So after the loop, if anything is left in the current word, it must be stored too. That line is easy to forget. Run it and all three words appear. Forget that line, and the last word silently disappears.

Common Mistakes

Three Faults in Word Splitting

This pattern attracts three faults. First, no flush after the loop: the final word is silently lost. Watch the same program with that line deleted. On the quick fox, the last word vanishes. But on input that ends with a space, everything works, which is exactly why it passes a casual test. With no emptiness check before storing, two consecutive spaces produce an empty entry in the vector, and so does a leading space. And forget to clear, and each word arrives with all the previous words stuck to the front of it.

Worked Example

Word Counts With Parallel Vectors

Next, a word frequency report: count how often each distinct word appears. Words can't index an array the way letters can, so the counting structure changes. Keep a vector of the distinct words, and a matching vector of counts. For each word, search the distinct list. If it's there, add one to the matching count. If not, push the word, and push a count of one, so both vectors stay in step. Position i in one corresponds to position i in the other. That pairing is worth stating out loud, because nothing in the code enforces it. Printed with setw, left-aligned words and right-aligned counts, the report lines up.

Worked Example

Anagrams Settled by Letter Tallies

Next, an anagram test: do two words use exactly the same letters? Rather than comparing the words, compare their letter counts. Two words are anagrams precisely when their 26-element tallies match. That reuses the frequency counter twice, then compares two arrays. An anagram uses the same letters the same number of times, and a tally records precisely that, while discarding order. Compare the tallies: listen matches silent and enlist, but not listed. One, one, zero.

Worked Example

Shifting Letters in a Substitution Cipher

Next, a substitution cipher: shift every letter forward by a key, wrapping past z, and leave everything else untouched. The function builds a new string, and leaves the input alone. A small letter is shifted relative to small a, and a capital relative to capital A. Anything else passes through. The remainder operator does the wrapping. Z shifted by 3 is position 25 plus 3, which is 28, and 28 mod 26 is 2, which is C. The two cases are kept separate, because capitals and small letters are different blocks. Arithmetic across the gap would push a letter out of its range.

Worked Example

Sorting Names by Character Code

Sorting names needs no new machinery at all, because string comparison already works on contents. Sorting Priya, Arjun, Meena and Kabir gives Arjun, Kabir, Meena, Priya. One caution. The ordering is by character code, so every capital sorts before every small letter. Zoya, with a capital, comes before arjun, with a small a. If a case-insensitive ordering is wanted, that's a different requirement, and it must be stated as one.

Practice

Three Tiers of Graded Exercises

Now the graded exercises, in three tiers. Attempt them without looking back at the worked solutions. Tier one is a warm-up: count vowels and consonants, find the longest word, and reverse each word while keeping their order. Tier two is the core: initials from a list of full names, a letter histogram sorted by count, and all 25 decodings of a cipher with an unknown key. Tier three is the challenge: a word frequency report that folds case, strips punctuation, ignores common words, and ranks the results. And grouping anagrams, so listen, silent and enlist end up on one line.

Testing Checklist

Edge Inputs to Test Before Submitting

Test every solution against these inputs before submitting. An empty line must give no crash, and a sensible report. A single character must use the same code path. Leading, trailing and doubled spaces must give no empty words, and no lost final word. Mixed case must be folded consistently where the requirement says so. Digits and punctuation must never be used to index a letter array. And text with no letters at all must still let every loop end, with no index leaving its range.

Lost Marks

Four Places Marks Slip Away

Marks are most often lost in four places. The final word: any splitting problem that forgets to store the partial word after the loop loses the last one. An unchecked character: counts of c minus a, on a space, gives a large negative index. Check the character is a letter first, every time. Case folded in one place only, when counting but not when reporting, gives answers right for some inputs and wrong for others.

Common Mistake

Unsigned Size on an Empty String

And mixed signedness. Size is unsigned, so size minus one on an empty string is an enormous number, not minus one. Hold it in an int, or check for emptiness first.

Quick Check

Shifting abc by a Key of 29

Quick check. Using the cipher function, what does shifting abc by a key of 29 produce? Pause and think. It produces def. Dividing 29 by 26 leaves a remainder of 3, so a key of 29 acts exactly like a key of 3.

Key Takeaways

Summary of Text Processing Patterns

To summarize. A letter minus a turns a character into an array index. Two indexes moving inward test a palindrome, with every loop bounded. When splitting, flush the last word after the loop. And words need parallel vectors of items and counts. Letter tallies settle anagrams, and the remainder operator wraps a cipher.

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
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

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.

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 Arrays With Text Processing

How do you turn a character into an array index to count letter frequency in C++?
Subtract 'a' from a lowercase letter to get an index from 0 to 25, which fits a 26-element counter array. For example, 'd' - 'a' is 3, so d's count lives at index 3. Check that the character is a letter first, fold it to lowercase, and initialize the array to zeros.
How do you test whether a string is a palindrome using two indexes in C++?
Start one index at the beginning and one at the end, then move them toward the middle, comparing letters. Each index skips non-letters, and the letters are compared after folding case. Stop at the first mismatch. Repeat the condition left < right inside the inner skipping loops, so a line of only punctuation never reads outside the string.
Why does my C++ code that splits a sentence into words lose the last word?
The last word has no separator after it, so the loop never stores it. After the loop, check whether the current word is non-empty and, if so, push it into the vector. Input ending in a space hides this bug, which is why a casual test can pass. Also check for an empty word before storing, and clear the word after each store.
How can you check whether two words are anagrams in C++?
Build a 26-element letter tally for each word and compare the two arrays. Two words are anagrams exactly when every count matches, because a tally records how many times each letter appears and discards order. With this method, listen matches silent and enlist, but listed does not match them, since its counts differ.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →