javaChipFrapp
javaChipFrapp

Reputation: 103

Checking for the end of a string without using arrays, etc

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

Answers (6)

Elvermg
Elvermg

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

Caleb Walker
Caleb Walker

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

ErstwhileIII
ErstwhileIII

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

paxdiablo
paxdiablo

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

Carter Sande
Carter Sande

Reputation: 1849

You could try comparing your index variable to s.length():

while (index < s.length()) {
    //process
}

Upvotes: 3

Jason
Jason

Reputation: 11832

  1. Use a for loop to iterate through all characters in the String until you get to String.length()
  2. Use a foreach loop to iterate through all characters that are returned from String.getBytes()

Upvotes: -1

Related Questions