The AP Computer Science A 5-hour live stream review is here!Β πŸ’»

Join us on May 5, 2021 for the 🌢️ AP Computer Science A Cram Finale for a last minute review to get all your questions answered!

πŸ“š

All Subjects

Β >Β 

πŸ’»Β 

AP Comp Sci A

Β >Β 

πŸ•Ή

Unit 4

4.3 Developing Algorithms Using Strings

2 min readβ€’november 16, 2020

Peter Cao


Using for loops, we can also develop many useful algorithms with Strings. There are several that you need to know in this course.

Reversing a String

To reverse a string, we need to go get the first character and make it into a String. Then we get the 2nd character and put it before the first character. Then we repeat until all the characters are used up.
public static String reverse(String s) { String result = "" for (int i = 0; i < string.length(); i++) { result = s.substring(i,i+1) + result; } return result; }

Get All Substrings of Length N

This can be used to print all characters in the string by setting the length n to 1. To get longer substrings, we increase n to the length of the substrings you want to find. This value can be up to the length of the overall string itself, but no more. This would create an exception. How this algorithm works is similar to a sliding window. The beginning of the window at the beginning of the substring you want to print and the end of the window is the end of the substring. Therefore the width of the rectangle is n. We first set the window to start at the beginning of the string. This corresponds to the loop initialization. Then, the window slides to the right by one character every iteration to represent the loop increment. The loop stops when the end of the window reaches the end of the string. To achieve this, we need the beginning of the window to be less than the length of the string + 1 - n.
public static void printSubstringsLengthN(String s, int n) { for (int i = 0; i < (s.length() + 1 - n); i++) { System.out.println(s.substring(i, i+n)); } }

Was this guide helpful?

πŸ’ͺ🏽 Are you ready for the Comp Sci exam?
Take this quiz for a progress check on what you’ve learned this year and get a personalized study plan to grab that 5!
START QUIZ
FREE AP comp sci a Survival Pack + Cram Chart PDF
Sign up now for instant access to 2 amazing downloads to help you get a 5
Browse Study Guides By Unit
πŸ™
Exam Reviews
πŸ–±
Unit 10: Recursion
βž•
Unit 1: Primitive Types
πŸ“±
Unit 2: Using Objects
πŸ–₯
Unit 3: Boolean Expressions and if Statements
βš™οΈ
Unit 5: Writing Classes
⌚️
Unit 6: Array
πŸ’Ύ
Unit 7: ArrayList
πŸ’»
Unit 8: 2D Array
πŸ–²
Unit 9: Inheritance
Join us on Discord
Thousands of students are studying with us for the AP Computer Science A exam.
join now