Videos
How do you find the length of a String in Java?
How do you find the length of a String array in Java?
What is the difference between String length() and array length in Java?
The length is just text.length(). Checking for a \0 terminator is a C-ism. Java doesn't terminate strings with NUL.
As stated in this SO,
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.
Therefore you can change the condition to
while (i < text.length())
(If your goal really is to get the length of a string, your function therefore is redundant, as it is already built in)
String s = "\\"; contains only the character \, and since it is a special one, it has to be escaped with the \ character.
In order to obtain a 2-sized String, you can escape two backslashes, like this:
String s = "\\\\";
This one doesn't have the size of 4, but 2, because there are characters (obviously, like the backslash) which are not represented by a single visual element in the editor.
There are also characters, which can be completely invisible when being printed (like the Mongolian vowel separator), but which are represented in a different way in the source (by their Unicode code). For example, the Mongolian vowel separator can be represented as:
String mongolianVowelSeparator = "\u180"; <-- one character only, invisible when printed
So here we have one character only (the U+180E Unicode character), but we used five editor characters to represent it.
Use the CharConverter from DrJava. You could adapt the source code for your project. It has a method that converts all the escaped chars in a string back to the real Java input.
String str1 = "\\";
String str2 = CharConverter.escapeString(str1);
System.out.println(str2.length()); // prints 2