My program needs to read a string and process each character, one at a time. I don't want to put the string into a char array, so is there any way to check for the end of the string without doing this? I tried to do this (where s is a String): s.charAt(index) != null as a condition for a while loop, but I shortly figured out that this obviously doesn't work, because you just can't use != with char and null. Is there any other way?
6 Answers
- Use a for loop to iterate through all characters in the String until you get to String.length()
- Use a foreach loop to iterate through all characters that are returned from String.getBytes()
6 Comments
jahroy
Seems like a senseless reason to throw an Ecxception. Why not just iterate over the each element after determining the length of the string.
Jason
Edited to offer options.
jahroy
Remove the try/catch approach and I'll remove my downvote. You should not use Exceptions in this scenario.
Jason
I will remove, however it is a valid demonstration of technique, even if not for this exact example.
jahroy
It is a possible approach, but it's a bad option here. We shouldn't teach the newb bad habits ;-)
|
for (int index = 0; index < s.length(); index++)...s.length()to determine the length of the string!!