I've defined String as
String s = "\\";
int length = s.length(); // returns 1
System.out.println(s); // prints only one "\"
How can I get it's size equal to 2
?
UPD: The problem is not in getting exactly 2-sized String. I need to get the count of source characters which I've defined my String by.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With