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

+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?

2/2/2020 10:44:36 AM

Sofonias

6 Answers

New Answer

+7

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

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

+3

Look also here for other string methods: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

+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.

+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

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.