Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating string with escape java

I have the following problem, I have a string array like that

String[] myArray = {"AAAA","BBBB","CCCC"};

and my purpose is to create another array like that

String myNewArray = {"\uAAAA","\uBBBB","\uCCCC"};

The problem is that if I try to create the array using a cycle

for (int i=0; i<myArray.length; i++) {
    myNewArray[i] = "\u" + myArray[i];
}

I receive an "Invalid unicode error", if I use a cycle like that

for (int i=0; i<myArray.length; i++) {
    myNewArray[i] = "\\u" + myArray[i];
}

I obtain this array

String myNewArray = {"\\uAAAA","\\uBBBB","\\uCCCC"};

And if I use this cycle

for (int i=0; i<myArray.length; i++) {
    myNewArray[i] = "\\u" + myArray[i];
    myNewArray[i] = myNewArray[i].substring(1);
}

I obtain this array

String myNewArray = {"uAAAA","uBBBB","uCCCC"};

Does anyone know how I can do that?

Thanks

like image 208
Daniele Milani Avatar asked Jun 20 '13 09:06

Daniele Milani


People also ask

How do I escape a character in a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do you use escape function in Java?

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must be enclosed in quotation marks ("").


2 Answers

You have to parse the strings as hexadecimal integers and then convert to chars:

String[] myArray = {"AAAA", "BBBB", "CCCC"};
String[] myNewArray = new String[myArray.length];
for (int i=0; i<myArray.length; i++) {
    char c = (char) Integer.parseInt(myArray[i], 16);
    myNewArray[i] = String.valueOf(c);
}
like image 180
Joni Avatar answered Oct 17 '22 18:10

Joni


\uAAAA is a literal, not a String with five chars. So we can't create it with concatenation. It is one char.

like image 24
Andreas Dolk Avatar answered Oct 17 '22 18:10

Andreas Dolk