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

I do not want to do this formally, using a for loop that processes all the elements of a string “a certain number of times” (string length).

Is there any character that is always at the end of every line in Java, just like in c?

+6
source share
4 answers

You have two main 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 an array of characters, and the second using a regular indexed loop.

However, Java does support characters such as '\ n' (newline). If you want to check for the presence of this character, you can use the indexOf ('\ n') method, which will return the position of the character, or -1 if it cannot be found. Be warned that the characters "\ n" are not required to end the line, so you cannot rely solely on this.

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

+6
source

Is there any character that is always in the tnd of each line in java, how does this happen in c?

No, that’s not how Java strings work.

I do not want to do this in a formal way, using for a loop that iterates over all the elements of a string “a certain number of times” (string length).

The only option is probably to add your own personal character:

 yourString += '\0'; 

(but be careful that yourString may contain \0 in the middle yourString

If you repeat characters in a string, you can also do

 for (char c : yourString.toCharArray()) process(c); 
+3
source
 String[] splitUpByLines = multiLineString.split("\r\n"); 

Will return an array of String s, each of which represents one string of your multi-line string.

0
source

System.getProperty("line.separator"); This will tell you an OS-independent new line symbol. You can probably check your string characters for this new line character.

0
source

Source: https://habr.com/ru/post/918100/


All Articles