public static int get(String A) // it is a method
{
int count = 1;
for (int i = 0; i < A.length(); i++) // So A reads line (any word, for example "Car"), so I understand that length will be 3 and that java will check all the characters.
{
int num = (A.charAt(i) - 'A') + 1;
count *= num;
}
return count;
}
Why do we write A.charAt(i) but not A.charAt[i]? And why do we write " - 'A' "?
1k views Asked by Anna Mokhubova AtThere are 7 answers
because charAt() is a method in java for string it and it returns a character. and 'A' refers to a char type while we write "A" for string type http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29
Java API for charAt() function
charAt() is a java method, not an Array
returns the char value at the specified index.
Syntax:
Here is the syntax of this method:
public char charAt(int index);
Because charAt is a method within string and it accepts index. String internally maintains char array and it's all hidden from us and hence you have a method not the array itself.
Reason for -'A'
is user wants to convert that character to integer. So for e.g. You character is 'B', User wants to convert it into int using ascii value of 'B' which is 66 - ascii value of 'A' which 65
num = 66 - 65 + 1
And do further processing.
The class String
is an immutable or value object. It doesn't give you direct access to the characters which make up the string, mainly for performance reasons but also since it helps to avoid a whole class of bugs.
That's why you can't use the array access via []
. You could call A.getChars()
but that would create a copy of the underlying character array.
char
is the code for a character. 'A' == 65
, for example. See this table. If A.charAt(1)
returns 'F'
(or 70), then 'F' - 'A'
gives you 5. +1 gives 6.
So the code above turns letters into a number. A pattern which you'll see pretty often is charAt(i) - '0'
to turn a string into a number.
But the code above is odd in this respect since count *= num
produces a pretty random result for the input. To turn the letters into numbers, base 26, it should read count = count * 26 + num
.
You write
A.charAt(i)
becausecharAt
is a function, not an array.You write
A.charAt(i) - 'A'
to compute the difference betweenA
'si
:th character and the character'A'
.