Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual length of the defined String in Java

Tags:

java

string

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.

like image 872
SeniorJD Avatar asked Dec 21 '15 10:12

SeniorJD


2 Answers

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.

like image 200
Konstantin Yovkov Avatar answered Oct 10 '22 04:10

Konstantin Yovkov


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
like image 41
ArcticLord Avatar answered Oct 10 '22 03:10

ArcticLord