Iterating through strings | Sololearn: Learn to code for FREE!


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?

2/2/2020 10:44:36 AM


6 Answers

New Answer


String input = "Hallo"; for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == 'a') { // Do stuff if reach char a }


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();


Look also here for other string methods:


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.


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:


Not all methods but just a few like this one and also datatype conversion would also be good. Thanks for the references, appreciate it.