tags:

views:

96

answers:

4

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 that 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?

+3  A: 

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().

Abel
+2  A: 

I think it's converting a char code to long. In Java you would have to:

long l = (long) myString.charAt(0)
helios
Thanks @ all for clarifying this. All answers were helpful and I mark this one as accepted for giving the example in Java.
Manuel
A: 

You can use this converter http://www.tangiblesoftwaresolutions.com/index.htm - the trial version is able to convert some amount of lines for free :)

dmitko
You could also use IKVM and not having to convert anything. It just works under .NET.
Abel
+1  A: 

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.

Nuno Ramiro