The line begins with an empty line ("")

My program reads a text file and performs text-based actions. But the first line of text is problematic. Apparently, this starts with "". This is messing my checks startsWith().

To understand the problem, I used this code:

   System.out.println(thisLine 
        + " -- First char : (" + thisLine.charAt(0) 
        + ") - starts with ! : " 
        + thisLine.startsWith("!"));

String thisLine - The first line in the text file.

he writes this to the console: ! use ! to add comments. Lines starting with ! are not read. -- First char : () - starts with ! : false

Why is this happening and how can I fix it? I want him to understand that the line starts with "!" not ""

+4
source share
5 answers

Gathering the comments of my and other people into one answer for posterity, your line probably contains non-printable control characters. Try

System.out.println( (int)thisLine.charAt(0) )

to print their numeric code or

my_string.replaceAll("\\p{C}", "?");

"?".

System.out.println( (int)thisLine.charAt(0) ) 65279 , , , . (. # 65279; HTML?).

, (my_string.replaceAll("\\p{C}", "");) @arvind (thisLine = thisLine.trim();) , .

: "" . , , Notepad ++.

+4

:

thisLine = thisLine.trim();
System.out.println(thisLine 
        + " -- First char : (" + thisLine.charAt(0) 
        + ") - starts with ! : " 
        + thisLine.startsWith("!"));
+2

, @. , .

But always remember that startWith (String arg) returns true if the arg argument is "" (empty string)

source: javadocs

+1
source

Ignore the first line if it is empty.

If you read lines in a loop, follow these steps:

thisLine = thisLine.trim();
if (thisLine.isEmpty()) {
    continue;
}
// Remaining logic here including sysout
0
source

Use the following code to see exactly what the first character of the string is and how long the string is:

System.out.println(thisLine 
    + " -- First char : (" + ((int)thisLine.charAt(0))
    + ") - Line length: " +  thisLine.length());
0
source

All Articles