UPI Study › Courses › C++ Programming › Free lessons › Lesson 7.3 Free with a free account
Assembling and Editing String Content
C++ Programming · Chapter 7: Text and Applied CollectionsSection 7.3 · lesson 45 of 84video coming soon
← Utilities for TextNext lesson: The String Class Toolkit →
In this lesson
Building, changing and rearranging text in code.
- Tell a new-string operation from an in-place one
- Insert, erase and replace, minding shifting positions
- Empty, resize, reverse and change case
- Join, split, and convert between text and numbers
Transcript
Everything said in the video, section by section (1,249 words). Read along, or search it.
Lesson Overview
Strings That Grow, Shrink, and Change
A string isn't a fixed row of characters that you're stuck with. It can grow, shrink, take an insertion in the middle, hand back a piece of itself, or be rebuilt entirely. It manages its own length while you do it. This lesson covers the operations that change a string's contents, the pattern for assembling one in a loop, and the conversions between text and numbers.
Key Distinction
New String Versus In-Place Change
Before any individual operation, one distinction organizes all of them. Some operations produce a new string, and leave their operands untouched. Others modify the string they're applied to, and produce nothing new. C equals a plus b produces a third string. Neither a nor b changes. A plus equals b modifies a in place: a is now longer, and no third string is produced. Confusing the two is the single most common source of, I changed it, and it didn't change.
Adding to the End
Four Ways to Append Text
Here are the four ways to add to the end of a string. Plus makes a new string. Use it when you want a joined result, while keeping the originals as they are. Plus equals modifies the string, building it up piece by piece. This is the everyday choice. Append does the same, spelled as a named operation. And push back adds a single character. Note the single quotes: one character, not a string of length one. Run it. Message holds the joined result, and greeting itself has grown.
Performance Tip
Prefer Plus Equals Inside Loops
Inside a loop, prefer the one that modifies. Writing result equals result plus piece, on every pass, builds a brand-new string each time and throws the previous one away. Writing result plus equals piece extends the string that's already there. For a handful of passes, the difference is invisible. For thousands, it's the difference between instant and sluggish, and the shorter form is easier to read anyway.
Positional Edits
Insert, Erase, and Replace at Positions
Three operations work at a stated position, rather than at the end. Positions count from zero, and each of these changes the string in place. Insert takes a position, then text. Inserting m at position 6 turns programing, with one m, into programming. The new text goes in before position 6, pushing everything from there rightward. Erase takes a position, then a count. Erasing two characters from position 0 turns unhelpful into helpful. Replace takes a position, a count, and the new text. Replacing three characters at position 7 with coffee turns I like tea into I like coffee. And replace doesn't require the new text to be the same length as the old.
Common Mistake
Positions Shift After Every Edit
Positions move as soon as you edit. Every one of these operations changes the length, so any position you worked out beforehand is only valid until the first edit lands. Remove three characters at position 4, and what used to be at position 20 is now at 17. Watch it on a real string. Delete the characters at positions 3 and 12. Going left to right, the second erase hits the wrong character, because everything shifted left. Working from the right-hand end backward removes exactly the two you meant. Or recompute each position immediately before using it. Applying a list of positions gathered in advance, left to right, is a reliable way to corrupt a string.
Changing Length
Pop Back, Resize, Swap, and Clear
Some operations change a string's length without adding new text. Starting from A B C D E: pop back removes the last character, giving A B C D. Resize 3 cuts the string down to A B C. Resize 8 with a dash extends it, filling the new positions: A B C D E, then three dashes. Swap exchanges the contents of two strings, and both are modified. Clear removes everything. The string still exists, and is now empty. And empty reports whether the length is zero. It's a question, not an instruction. Those last two names read alike, and don't behave alike. Writing s dot empty as a statement on its own is legal, and does nothing whatsoever. This compiler warns about it, because the answer is thrown away. It's a genuinely common slip, so read warnings like this one, rather than scrolling past them.
Transformations
Reversing and Changing Case
Two whole-string transformations come up constantly: turning a string back to front, and converting every character to one case. Std reverse takes the beginning and the end of the string, and turns the contents around in place. Stressed becomes desserts. Case conversion has no whole-string operation of its own. It's done one character at a time: read each position, convert it, and write it back. Toupper has no idea a string is involved, which is why the loop does the traveling. The counter uses size t, the type for lengths and positions.
Worked Example
Joining Names with a Separator
Building one string from many uses the same accumulator pattern as numeric totals: start empty, and add on every pass. The only wrinkle is the separator, which belongs between items, and so must not appear before the first. Here, four names are joined. If i is greater than zero, a comma and space are added first. Then the name. The result is Neha, Varun, Komal, Maitri. The test i greater than zero is what keeps the result from beginning with a stray comma.
Splitting Strings
Getline and Stringstream Delimiters
Splitting runs the other way: one string in, several pieces out. A stringstream wraps a string, and then behaves like any other stream. That means getline can read from it. And getline accepts a third argument, saying which character ends each piece. So, reading red comma green comma blue with a comma as the delimiter gives red, then green, then blue. Splitting and joining are the same journey in opposite directions, and the separator is the hinge.
Conversions
Moving Between Text and Numbers
Text and numbers are different things, and neither turns into the other by accident. The string 42 is two characters. The number 42 is a value you can do arithmetic on. To string turns a number into text: 2026 becomes the text 2026. It accepts fractional values too, with a fixed number of decimal places. Stoi turns text into a whole number. It reads leading digits, and stops at the first character that can't belong. So 42kg gives 42. Stod does the same for fractional numbers, accepting a decimal point.
String Streams
Mixed Types in One Line
A stream is the tool when several values are involved at once, in either direction. Writing into one assembles a line out of pieces of different types: order 17, total 249.75. Reading out of one takes a line apart into variables of different types. 17 goes into the order I D, and 249.75 into the total, as numbers.
Failed Conversions
When Text Isn't a Number
What if the text isn't a number at all? Handing stoi the word hello throws an exception, rather than returning zero. A stream fails differently: no exception. The variable receives zero, and the stream is marked as failed. Both are taken up where input checking is treated properly. For now, convert values you already know to be numeric.
Quick Check
Erasing B and E from ABCDEFG
Quick check. s holds "ABCDEFG". You call s.erase(1, 1), then s.erase(4, 1), to remove B and E. What's left? Pause and work it out. It's ACDEG. Removing B shifted everything left, so position 4 now held F, not E. Erase from the right, position 4 first, and B and E both go.
Key Takeaways
Summary of String Editing Tools
To summarize. Plus makes a new string. Plus equals, append, and push back modify the string in place. Insert, erase and replace shift every later position, so work from the right, or recompute. Clear empties a string. Empty only asks. Join with a separator before all but the first item. And convert with to string, stoi, stod, and string streams.
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 Assembling and Editing String Content
What is the difference between c = a + b and a += b for C++ strings?
Why does erasing several characters from a C++ string remove the wrong ones?
How do I split a comma-separated string in C++?
How do I convert between strings and numbers in C++, and what happens with bad input?
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 →