Assembling and Editing String Content | C++ Programming

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 →

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

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.

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 Assembling and Editing String Content

What is the difference between c = a + b and a += b for C++ strings?
The expression c = a + b creates a new string and leaves a and b unchanged, while a += b modifies a in place and creates no third string. Append does the same job as plus equals, and push_back adds a single character. Inside loops, prefer result += piece over result = result + piece, because the longer form builds and discards a new string on every pass.
Why does erasing several characters from a C++ string remove the wrong ones?
Each erase shifts every later character toward the front, so positions worked out beforehand go stale. If s holds ABCDEFG, calling s.erase(1, 1) and then s.erase(4, 1) leaves ACDEG, not ACDFG, because F had moved into position 4. Erase the higher position first, working right to left, or recompute each position just before you use it.
How do I split a comma-separated string in C++?
Wrap the string in a stringstream, then call getline on it with the delimiter as the third argument. For example, stringstream ss("red,green,blue"); string part; while (getline(ss, part, ',')) { cout << part << endl; } prints red, green, and blue on separate lines. You need the sstream header, and the delimiter character marks where each piece ends.
How do I convert between strings and numbers in C++, and what happens with bad input?
Use to_string to turn a number into text, so to_string(2026) gives the text 2026. Use stoi for whole numbers and stod for fractional ones. They read leading characters that fit and stop at the first one that does not, so stoi("42kg") gives 42. Calling stoi on "hello" throws an exception instead of returning zero.

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 →