7

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 ?

2
  • The end of a line in a file or the end of a string? Commented Jun 14, 2012 at 13:30
  • Do you mean end of line? Like if you have multiple lines in the same string? Commented Jun 14, 2012 at 13:32

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you need to use the length() method to find out how long a string is. -- No you don't.
I know you have other options to find the length of a String, just like you don't NEED a Java compiler, you can just write the bytecodes by hand, but using Str.length() is simple and easy and really, this is a beginner coder, why confuse him or her?
4

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);

Comments

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

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

1 Comment

Don't think this is what the OP wants. He probably expects NUL terminated string like in C.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.