user1448750
user1448750

Reputation:

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

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 ?

Upvotes: 7

Views: 73821

Answers (4)

RP-
RP-

Reputation: 5837

System.getProperty("line.separator"); This will tell you OS independent new line character. You can probably check your string's characters against this new line character.

Upvotes: 0

Ewald
Ewald

Reputation: 5751

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.

Upvotes: 7

aioobe
aioobe

Reputation: 420991

Is there any character that is always at the tnd of every string in java just like it it in c ?

No, that is not how Java strings work.

I don't want to do it the formal way by using for loop that goes over all the elements of the string a "particular no. of times"(length of string) .

The only option then is probably to append a special character of your own:

yourString += '\0';

(but beware that yourString may contain \0 in the middle as well ;-)

If you're iterating over characters in the string, you could also do

for (char c : yourString.toCharArray())
    process(c);

Upvotes: 4

Hans Z
Hans Z

Reputation: 4744

String[] splitUpByLines = multiLineString.split("\r\n");

Will return an array of Strings, each representing one line of your multi line string.

Upvotes: 0

Related Questions