Extract characters from string
Sometimes you need to get one character from a string. For example, if the site knows the user’s first and last name, and at some point you need to display this information in the format
A. Ivanov, then you need to take the first character from the name.
var firstName = "Alexander"; System.out.print(firstName.charAt(0)); // => A
charAt(int index) is a special method for extracting a character from a string. Index is the position of the character within the string. Indices start with 0 in almost all programming languages - therefore, to get the first character, you need to specify the index
An index can be not only a specific number, but also the value of a variable. Here is an example that will lead to the same result - displaying the
A symbol on the screen, but the index inside the square brackets is written not by a number, but by a variable:
var firstName = "Alexander"; var index = 0; System.out.print(firstName.charAt(index)); // => A
Although the character is not a string, the concatenation operation (+) can work if one of the arguments is a character. It will make a string of it and compute it as a concatenation of two strings. But don’t try to concatenate characters with each other, not with a string - the Java compiler will decide that you want to add the numeric codes of these characters, and the result will be some number.
System.out.print('H' + 'A'); // => 137 System.out.print('H' + " " + 'A'); // => "H A"
You are given three variables with the names of different people. Compose and display a word of characters in this order:
- the third character from the first line;
- the second character from the second line;
- the fourth character from the third line;
- the fifth character from the second line;
- the third character from the second line.
The output should be something like this: “a b c d e”
Exercise available only for signed users.
Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on Github.