Ntokozo Matshika
Ntokozo Matshika

Reputation: 11

reversing a single character in Java

Is there any way to reverse a character in Java, i.e reversing "(" into ")". I tried String buffer, of course it did not work because it does not reverse a character but a string of more than one character. Your help will be much appreciated.

Upvotes: 1

Views: 287

Answers (2)

Stephen C
Stephen C

Reputation: 718788

Is there any way to reverse a character in Java

The simple answer is No. Not in any of the standard APIs. (And AFAIK not in any of the commonly used 3rd-party libraries; Apache Commons, Guava, etcetera.)

Why?

  • Because this kind of thing is rarely called for. (I don't recall ever seeing a request like this before on StackOverflow.) The Java designers wisely do not front-load the standard APIs with obscure methods that are rarely if ever going to be used.

  • Because the notion of "reverse" is not well defined:

    • If you want a character whose glyph is the mirror image of some other character, that is not a tractable problem. The glyphs depend on the Font used. For example a ( and ) are not mirror images. (At least on my screen they aren't!)
    • If you want something where one code point inherently1 means the opposite or reverse of another, that is intractable because code points don't have any inherent meaning2.

1 - What is the opposite of "N"? Is it "Y"? Would someone in France agree? What about "A"? A geneticist would give you a different answer to a numerologist. My point: there are many ways to ascribe meaning to code points.

2 - Apart from corresponding to an abstraction (a letter, a number, a symbol, etcetera) which typically also doesn't have a single inherent meaning.


So what is the solution?

Implement your own notion of "reverse" for yourself using a simple lookup table.

Upvotes: 1

kkica
kkica

Reputation: 4104

Not really.

You cannot do that unless you provide a map of the characters you want to replace and with what you want to replace them.

Then you iterate the string, find if the char has a "reverse" char in your map, and if so, replace it.

Upvotes: 1

Related Questions