Метод charAt() в Java
Есть множество базовых методов, которые мы регулярно используем, даже не задумываясь. Ну а что, если задуматься и посмотреть, каким образом реализованы некоторые простые, на первый взгляд, методы? Думаю, это поможет нам стать на шаг ближе к Java) Представим ситуацию, в которой нам нужно вытащить определенный символ в какой-то строке. Как мы это можем сделать в Java? Например, с помощью вызова метода Java String charAt . О методе charAt() мы и поговорим в сегодняшней статье.
Синтаксис
Пример
Что “под капотом”
Как же оно работает, спросите вы?Дело в том, что в каждом объекте String есть массив byte с байтами элементов данной строки: А вот и сам метод chatAt : isLatin1 — флаг, указывающий на то, есть ли в нашей строке только латинские символы или нет. От это зависит, какой метод будет вызываться далее.
isLatin1 = true
- & расширяет для двоичной операции для byte побитово
- 0xff ничего не делает, но & требует аргумент
- (char) приводит данные по таблице ASCII к char
isLatin1 = false
- для ‘а’ это пара байтов — 48 и 4;
- для ‘в’ — 50 и 4.
В примере с строкой «абвг» , шестой байт — 51 — так бы и остался, но при этом увеличивается индекс до 7.
И если у нас это был байт 4, который имеет двоичное представление — 00000000 00000100, то после сдвига на 8 битов у нас будет 00000100 00000000. Если целым числом — 1024.
И если у нас были байты 51 и 1024, которые в двоичном представлении выглядели как 00000000 00110011 и 00000100 00000000, то после операции OR мы получим 00000100 00110011, что значит число 1075 в десятичной системе.
Ну и в конце концов, переводится число 1075 в тип char, а при переводе int -> char используется таблица ASCII, и в ней под номером 1075 стоит символ ‘г’.
Java String charAt() Method example
The Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1). For example: s.charAt(0) would return the first character of the string represented by instance s. Java String charAt method throws IndexOutOfBoundsException, if the index value passed in the charAt() method is less than zero or greater than or equal to the length of the string ( index<0|| index>=length() ).
Java String charAt() Method example
Lets take an example to understand the use of charAt() method. In this example we have a string and we are printing the 1st, 6th, 12th and 21st character of the string using charAt() method.
Output:
IndexOutOfBoundsException while using charAt() method
When we pass negative index or the index which is greater than length()-1 then the charAt() method throws IndexOutOfBoundsException. In the following example we are passing negative index in the charAt() method, lets see what we get in the output.
Output:
Java String charAt() example to print all characters of string
To print all the characters of a string, we are running a for loop from 0 to length of string – 1 and displaying the character at each iteration of the loop using the charAt() method.
Java String charAt() example to count the occurrence of a character
In this example, we will use the charAt() method to count the occurrence of a particular character in the given string. Here we have a string and we are counting the occurrence of character ‘B’ in the string.
Output:
Java.lang.String.charAt() Method
The java.lang.String.charAt() method returns the char value at the specified index. An index ranges from 0 to length() — 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
Declaration
Following is the declaration for java.lang.String.charAt() method
Parameters
index − This is the index of the char value.
Return Value
This method returns the char value at the specified index of this string. The first char value is at index 0.
Exception
IndexOutOfBoundsException − if the index argument is negative or not less than the length of this string.
Java String: charAT() Method
The charAT() method is used to get the char value at the specified index. An index ranges from 0 to length() — 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Java Platform: Java SE 8
Syntax:
Parameters:
Name | Description | Type |
---|---|---|
index | the index of the char value. | int |
Return Value:
The char value at the specified index of this string. The first char value is at index 0.
Return Value Type: char
Throws: IndexOutOfBoundsException — if the index argument is negative or not less than the length of this string.
Pictorial presentation of Java String charAT() Method
Example: Java String charAT() Method
Example of Throws: charAt(int index) Method
IndexOutOfBoundsException — if the index argument is negative or not less than the length of this string.