Lesson 5.2 · Write it
First N characters
A functionPython or Java7 tests, 4 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the first n characters of a text value.
texthas at least one character. It contains only English letters, digits, spaces and punctuation.nis at least 1, and at most the number of characters intext.
Only the value your function returns is checked.
def first_n_chars(text: str, n: int) -> str
Examples
Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- first_n_chars("hello", 3) should return "hel": the first 3 of 5 characters (rule 2)
- first_n_chars("abcdef", 1) should return "a": n is 1, the smallest it can be (rule 2)
- first_n_chars("xyz", 3) should return "xyz": n is the whole length, so the whole text comes back (rule 2)
public static String firstNChars(String text, int n)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- firstNChars("hello", 3) should return "hel": the first 3 of 5 characters (rule 2)
- firstNChars("abcdef", 1) should return "a": n is 1, the smallest it can be (rule 2)
- firstNChars("xyz", 3) should return "xyz": n is the whole length, so the whole text comes back (rule 2)