Convert expression from C# into Java
I am to convert a C# program into Java. At one point I really don't get what is done, there. I changed the code to clarify the types and give an example.
string myString = "Test";
long l = (long)myString[0];
1) What is the [0] doing with a normal string? Is t开发者_如何学编程hat even possible? Is it just the substring, in this case "T"?
2) How could you cast a String or character to long, if the String represents a text?
long l = (long)myString[0];
the index of a string gives the char. A char
is castable as a long
. This will give you the long-value (unicode value) of the character in the first position of the string, i.e., A
will be 65
.
The cast (long)
is not needed in C#, because char
has what's called a "implicit cast operator" for long
and int
. The following statement is just as well correct:
long l = myString[0];
The equivalent of char
in C# is char
in Java, albeit that implementations are slightly different. In Java, a char can be cast to an int
or a long
. To get the character, use CharAt()
.
I think it's converting a char code to long. In Java you would have to:
long l = (long) myString.charAt(0)
A string is an array of characters, so that makes it possible to access given position.
Having said that, myString[0] is accessing the first char, 'T'.
You can then cast a char to a long, converting it to its ASCII position value.
You can use this converter http://www.tangiblesoftwaresolutions.com/index.htm - the trial version is able to convert some amount of lines for free :)
精彩评论