Jehan Jaleel wrote:
This string has a length of 35, but when you print it in a file it takes up 51.
No, it has a length of 35 because that is the number of characters in the String. If you use a PrintWriter, BufferedWriter, etc., then Java will write out the 35 chars you give it.
Because the tabs are not interpreted until it is written to a file.
False. Tabs are not expanded until the file is read and its contents displayed in a text editor. (Or until it is read by some other tool that chooses to expand tabs.) And this does not affect the contents of the file. It still contains the 35 chars, including the tab characters. Now, if you save it from your text editor, you might have it configured to save it back as spaces instead of tabs, but again, that is the tool explicitly replacing those tab characters with spaces.
How can I know this length when printed?
You mean how can you know the length when displayed? You can't, because you can't know which tool will be used to display it or how it will be configured.
One way would be to count characters as you loop through the String. Once you encounter a tab you need to treat the counter specially. Assuming you want tabs to fill up to 8 spaces, that would mean adding 1 for the tab itself and then rounding up to the nearest multiple of 8.