Why do we write A.charAt(i) but not A.charAt[i]? And why do we write " - 'A' "?

1k views Asked by At
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;
    }
7

There are 7 answers

0
molbdnilo On BEST ANSWER

You write A.charAt(i) because charAt is a function, not an array.

You write A.charAt(i) - 'A' to compute the difference between A's i:th character and the character 'A'.

0
Zahid Ali On

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

0
Luke SpringWalker On

A.charAt(i) is a method for strings, you could also do A[i] to access the same position directly.

When you do an operation (+ or -) with chars, you get an int.

0
Naveen Kumar Alone On

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);
0
Julian Kroné On

Because charAt() is a method that returns a character from a given String, and not an array. Characters are written 'A'. Strings are written "A".

0
SMA On

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.

0
Aaron Digulla On

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.