Creating a string with escape-java

I have the following problem: I have such an array of strings that

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

and my goal is to create another such array

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

The problem is that if I try to create an array using a loop

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

I get "Unacceptable Unicode Error" if I use such a loop

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

I get this array

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

And if I use this loop

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

I get this array

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

Does anyone know how I can do this?

thanks

+6
source share
6 answers

You need to parse the strings as hexadecimal integers and then convert to char s:

 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); } 
+7
source

\uAAAA is a literal, not a five-character string. Therefore, we cannot create it with concatenation. This is one char.

+1
source

The \ character must be escaped.

Therefore, running myNewArray[i] = "\\u" + myArray[i] is what you want to do.

Try printing it to clear the contents.

0
source

Actually, I cannot solve your problem, but I can tell you the following: Your first approach is trying to concatenate the unicode string "\ u" (in your case empty <=> is invalid) with the nonunicode string. Your second approach is really correct. System.out.println ("\ u" + "AAAA") should print \ uAAAA As a result, you can say that your code is correct, I suggest looking for coding options in the development environment / IDE.

0
source

You can simply copy and paste the program below. I checked the code ... and it works great

public class Main {

 static String a[]; private static String[] myNewArray; public static void main(String[] args) { String[] myArray = {"AAAA", "BBBB", "CCCC"}; myNewArray = new String[myArray.length]; for (int i = 0; i < myArray.length; i++) { myNewArray[i] = "\\u" + myArray[i]; } for (int i = 0; i < myArray.length; i++) { System.out.println(myNewArray[i]); } } 

}

0
source
 String[] myArray = {"AAAA","BBBB","CCCC"}; String[] myNewArray = {"\uAAAA","\uBBBB","\uCCCC"}; String we="\\u"; for (int i=0; i<myArray.length; i++) { myNewArray[i] = we + myArray[i]; } 
-2
source

Source: https://habr.com/ru/post/947715/


All Articles