How to check if I have reached the end of a String in Java ?

java, string

Solution

You have two basic options:

String myString = "ABCD";
for (char c : myString.toCharArray())
{
  System.out.println("Characer is " + c);
}

for (int i = 0; i < myString.length(); i++)
{
  System.out.println("Character is " + myString.charAt(i));
}

The first loops through a character array, the second loops using a normal indexed loop.

Java does however, support characters like '\n' (new line). If you want to check for the presence of this character, you can use the indexOf('\n') method that will return the position of the character, or -1 if it could not be found. Be warned that '\n' characters are not required to be able to end a string, so you can't rely on that alone.

Strings in Java do NOT have a NULL terminator as in C, so you need to use the length() method to find out how long a string is.

Problem

I don't want to do it the formal way by using a `for` loop that goes over all the elements of the string a "particular no. of times"(length of string) . Is there any character that is always at the end of every string in Java just like it it in c ?

Original source

Related problems