Iterating through strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Iterating through strings

In Java, How can I look through each character in a string with a for loop? Or assign a variable to a specific character within the string?

2nd Feb 2020, 10:44 AM
Sofonias
Sofonias - avatar
6 Answers
+ 7
String input = "Hallo"; for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == 'a') { // Do stuff if reach char a }
2nd Feb 2020, 10:48 AM
r8w9
r8w9 - avatar
+ 7
String s = "hello"; //use .charAt() char c = s.charAt(3); //l //loop from 0 to length - 1 for(int i = 0; i < s.lengt(); i++){ System.out.println(s.charAt(i)); } You can also get a char array from the string: char[] letter = s.toCharArray();
2nd Feb 2020, 10:50 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
2nd Feb 2020, 10:53 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Awesome. Thanks guys I was really getting fed up cause I couldn't do a thing with strings other than printing them 😅 I also think that would be the problem with a lot of other beginners learning on solo learn because none of it is found on the lessons.
2nd Feb 2020, 11:04 AM
Sofonias
Sofonias - avatar
+ 2
Presenting all methods would go beyond the scope of the courses. It is important that you learn to use java documentation in addition to SL. Here are a few other Java resources: https://www.sololearn.com/discuss/580291/?ref=app
2nd Feb 2020, 11:34 AM
Denise Roßberg
Denise Roßberg - avatar
0
Not all methods but just a few like this one and also datatype conversion would also be good. Thanks for the references, appreciate it.
2nd Feb 2020, 11:37 AM
Sofonias
Sofonias - avatar