Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String starts with an empty String ("")

Tags:

java

string

text

My program is reading a text file and doing actions based on the text. But the first line of the text is problematic. Apparently it starts with "". This is messing my startsWith() checks.

To understand the problem I've used this code :

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

String thisLine is the first line in the text file.

it 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 do I fix this? I want it to realize that the line starts with "!" not ""

like image 328
WVrock Avatar asked Mar 15 '23 15:03

WVrock


1 Answers

Collecting mine and others' comments into one answer for posterity, your string probably contains unprintable control characters. Try

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

to print out their numerical code or

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

to replace the control characters with '?'.

System.out.println( (int)thisLine.charAt(0) ) printed 65279 for you which would be the Unicode code point for a zero-width space, not unprintable but effectively invisible on output. (See Why is  appearing in my HTML?).

Either remove the extra whitespace character from the file, remove all control characters from the string (my_string.replaceAll("\\p{C}", "");) or use @arvind's answer and trim the string (thisLine = thisLine.trim();) before reading so it contains no whitespace at the very beginning or the very end of the string.

EDIT: Notepad won't show most 'special' characters. If you want to edit the file try a hex editor or a more advanced version of notepad such as Notepad++.

like image 165
Buurman Avatar answered Mar 23 '23 18:03

Buurman