Task 8 of 15 · 0 solved · 15 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

1.5 Strings — length, characters and substrings

Lesson

Taking a string apart

A string is a sequence of characters, numbered from 0. Three tools open it up: length() gives the number of characters, charAt(i) gives the single character at position i, and substring(from, to) gives the piece between two positions.


Worked example

String w = "programming";
System.out.println(w.length());          // 11
System.out.println(w.charAt(0));         // p
System.out.println(w.substring(0, 7));   // program
System.out.println(w.substring(3));      // gramming

⚠️ The end index of substring is not included: substring(0, 7) takes positions 0 through 6. With one argument it runs to the end.

Note the types differ: charAt returns a single char (written in single quotes, 'p'), while substring(0, 1) returns a one-character String ("p"). They print the same but are not the same type.


▶ Try it: run this, then change something and run it again.



Positions in a string are numbered from...


"hello".substring(1, 3) gives...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    String s = "abcdef";
    System.out.println(s.length());
    System.out.println(s.charAt(2));
    System.out.println(s.substring(2, 4));
}}

Difference between charAt(0) and substring(0, 1)?


True or false?