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