Accessing Characters
Lesson 5 of 16 in Coddy's Strings and Arrays in Java course.
To access separate characters in a string, we can use index.
The index of the first character is 0, the second character is 1, and so on.
To access it, use the charAt() method,
String myStr = "Hello";
char result = myStr.charAt(0);In the above example, result will hold the character H.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyWrite a function named blurb that gets a string as an argument. The function returns the concatenation of the characters in the 1st, 3rd and 5th indexes.
Because the charAt() returns a char, you need to cast it to a string in order to perform the concatenation, this is how it's done:
char c1 = 'a';
char c2 = 'b';
char c3 = 'c';
String concatenation = String.valueOf(c1) + String.valueOf(c2) + String.valueOf(c3);
System.out.println(concatenation) // Outputs abcTry it yourself
class Blurb {
public static String blurb(String s) {
// Write code here
}
}