Skip to Content

Using Loops With Strings

Put your knowledge of String traversal to the test with these code challenges.

String Traversal

Strings are objects that hold text-based information. Did you know we can also iterate through a String using a loop? That’s right- similar to arrays and ArrayLists, we can traverse a String in order to access each individual element.

This ability to traverse a String can be extremely useful. For example, an attempt was made to copy and send over the full poem of “The Raven” by Edgar Allan Poe; however, it was reported that two of the stanzas showed up like this:

".<romr<v<N" sa <man hcus htiW ,rood r<bmahc sih <voba tsub d<rutplucs <ht nopu tsa<b ro driB —rood r<bmahc sih <voba drib gni<<s htiw d<ss<lb saw t<y r<v< gni<b namuh gnivil on taht gni<<rga pl<h tonnac <w roF ;<rob ycnav<l<r <lttil—gnina<m <lttil r<wsna sti hguohT ,ylnialp os <sruocsid ra<h ot lwof ylniagnu siht d<ll<vram I hcuM ".<romr<v<N" n<vaR <ht htouQ "!<rohs nainotulP s'thgiN <ht no si <man yldrol yht tahw <m ll<T —<rohs ylthgiN <ht morf gnir<dnaw n<vaR tn<icna dna mirg yltsahG ,n<varc on <rus tra" ,dias I ",uoht ,n<vahs dna nrohs <b ts<rc yht hguohT" ,<row ti <cnan<tnuoc <ht fo muroc<d nr<ts dna <varg <ht yB ,gnilims otni ycnaf das ym gniliug<b drib ynob< siht n<hT

We’ve been tasked with resolving the problem using String traversal. Let’s get started!

Create a new string with the characters reversed

The first known issue is that the poem text became reversed. We’ll use an algorithm to reverse all the characters. We’ll need to take the following steps:

  1. Declare a new, empty String to store the reversed text.
  2. Create a for loop that will iterate through every value of our String.
  3. Inside the loop, grab a single element at the String index of the current iteration.
  4. Also within the loop, update the new String by prepending the current element’s value to the current String value.
  5. Return the new String once the loop is complete.

Ready to Learn More?

Find the course that's right for you! Explore our catalog or get a recommendation.