Reputation: 103
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?
Upvotes: 0
Views: 77
Reputation: 447
You can use the String's method length to check the size of the string. for example:
for(int i = 0; i < s.length(); i++) {
char h = s.charAt(i);
//process h
}
Upvotes: 3
Reputation: 73
You need to use String's .length() method.
String s = "test";
for(int i=0; i < s.length ; i++){
char c = s.charAt(i);
}
Upvotes: 3
Reputation: 4843
The simplest loop through a string one character at a time would simply use the length of the string to handle this. For example:
if (inputString != null) {
for (int i=0; i < imputString.length(); i++) {
theChar = inputString.charAt(i);
...
}
}
Upvotes: 2
Reputation: 881113
You don't need to "put the string into a char array", you can use the string length as a limiter, and charAt
to process each character:
for (int chPos = 0; chPos < str.length(); chPos++)
doSomethingWith (str.charAt(chPos));
Upvotes: 3
Reputation: 1849
You could try comparing your index
variable to s.length()
:
while (index < s.length()) {
//process
}
Upvotes: 3
Reputation: 11832
Upvotes: -1