about | help | code help+videos | done | prefs |
crehwinkel@frhsd.com ap-exam-review-set3
Description:AP Exam Review Set 3
How to use a for loop with a String
If the input is named str (and it will be, most of the time), here's a simple for loop that goes through all characters and checks an individual character using str.substring(i, i+1).for (int i = 0; i < str.length(); i++) { if (str.substring(i, i+1).equals("A")) { // do something when we find the character 'A' inside str // note, substring returns String and thus compares using .equals } }
Alternately, you could also do this inside the loop (using charAt instead of substring)
for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 'A') { // do something when we find the character 'A' inside str // note, charAt returns char and thus compares using == } }
Strings
firstWord H
countWords
getSandwich
Copyright Nick Parlante 2017 - privacy