Editing Unicode within a String

I wanted to have a List with Unicode Strings, but I wondered if I could use a for loop instead of adding 9 variables by hand. I tried the following code, but it didn't work.

List<String> reactions = new ArrayList<>();

for (int i = 1; i < 10; i++) {
    reactions.add("\u003" + i + "\u20E3");
}

My IDEA gives me an 'illegal unicode escape' error.
Is there an other way to accomplish this?

Upvotes: 0

Views: 134

Answers (2)

jhamon
jhamon

Reputation: 3691

Assuming you want to display the character \u003i, with ifrom 1 to 9, and \u20E3, remember a character is like a number and can be used in mathematical operation.

  • get the character \u0030: '\u0030'
  • add i : '\u0030' + i
  • concatenate the new character with the other one (as a string)

Then print the result:

System.out.println((char)('\u0030' + i) + "\u20E3");

Upvotes: 0

VGR
VGR

Reputation: 44308

The easiest way to convert a number to a character within a string is probably using a Formatter, via String.format:

List<String> reactions = new ArrayList<>();

for (int i = 1; i < 10; i++) {
    reactions.add(String.format("%c\u20e3", 0x0030 + i));
}

Upvotes: 1

Related Questions