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 ?

Ankit
  • 6,772
  • 11
  • 48
  • 84

4 Answers4

8

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.

Ewald
  • 5,691
  • 2
  • 27
  • 31
  • *you need to use the length() method to find out how long a string is.* -- [No you don't](http://stackoverflow.com/questions/2910336/string-length-without-using-length-method-in-java). – aioobe Jun 14 '12 at 13:34
  • 3
    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? – Ewald Jun 14 '12 at 13:38
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);
aioobe
  • 413,195
  • 112
  • 811
  • 826
0
String[] splitUpByLines = multiLineString.split("\r\n");

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

Hans Z
  • 4,664
  • 2
  • 27
  • 50
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.

RP-
  • 5,827
  • 2
  • 27
  • 46