Teacher Guide: String Methods

Student page: String Methods IB Syllabus: B2.1.2 Estimated periods: 2 (90 min each) Prerequisites: Variables & Data Types

Contents

  1. Lesson Plans
    1. Period 1: Core String Methods
    2. Period 2: String Processing with Loops
  2. Differentiation
    1. Supporting Weaker Students
    2. Extending Stronger Students
  3. Answer Keys
    1. Core 1: String Length
    2. Core 2: First and Last
    3. Core 3: Initials
    4. Core 4: Substring Extractor
    5. Extension 5: Word Count
    6. Extension 6: Email Parser
    7. Extension 7: Palindrome Checker
    8. Challenge 8: Caesar Cipher
    9. Challenge 9: Title Case
  4. Integration Notes
    1. Additional Resources

Lesson Plans

Period 1: Core String Methods

Phase Time Activity Student Page Section
Warm-up 10 min “Alice Johnson” on board – how to extract first/last name?
Teach 25 min length(), charAt(), substring(), indexOf(), equals() Key Concepts
Practice 40 min Core #1-4 Practice Exercises
Wrap-up 15 min Quick Code Check MCQs Quick Code Check

Additional activities:

  • Live coding walkthrough: concatenation, immutability, length, indexOf, substring
  • Password creator exercise: build a password from substring of family name + birth year + special character
  • Discussion: “Why is String manipulation important for user-facing solutions?”

Period 2: String Processing with Loops

Phase Time Activity Student Page Section
Warm-up 10 min Parse “alice.johnson@school.edu” – extract username/domain
Teach 15 min String traversal with charAt() loop, building new strings Worked Examples
Practice 50 min Extension #5-7, Challenge #8-9 Practice Exercises
Wrap-up 15 min Trace exercise from student page Trace Exercise

Additional exercises:

  • Password length comparison, case conversion, file extension extraction

Differentiation

Supporting Weaker Students

Strategy When to use Example
Method reference card Can’t remember which method does what One-page: length(), charAt(i), substring(s,e), indexOf(s), equals(s)
Index diagram Struggles with substring indices Draw “H-e-l-l-o” with indices 0-4 above each letter
Reduce exercise set Overwhelmed Focus on Core #1-3 only, skip #4
Pair programming During Extension exercises Stronger student explains charAt loop pattern

Extending Stronger Students

Strategy When to use Example
Password creator Finishes Core early Build a password from substring of family name + birth year + special char
Challenge exercises Extended learners #8 Caesar cipher, #9 Title case
String immutability investigation After Core concepts “Why doesn’t str.toUpperCase() change str?” – discuss immutability
Real-world parsing After Extension #6 Parse a CSV line: “Alice,16,Grade11” into separate fields

Answer Keys

Core 1: String Length

Show solution
import java.util.Scanner;
public class StringLength {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        System.out.println("Length: " + word.length());
        scanner.close();
    }
}

Expected output: “hello” -> Length: 5

Common mistakes: Using word.length without parentheses (that’s array syntax, not String syntax).


Core 2: First and Last

Show solution
import java.util.Scanner;
public class FirstAndLast {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        System.out.println("First: " + word.charAt(0));
        System.out.println("Last: " + word.charAt(word.length() - 1));
        scanner.close();
    }
}

Common mistakes: Using word.charAt(word.length()) – off by one, throws StringIndexOutOfBoundsException.


Core 3: Initials

Show solution
import java.util.Scanner;
public class Initials {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter full name: ");
        String fullName = scanner.nextLine();
        int spaceIndex = fullName.indexOf(" ");
        char firstInitial = fullName.charAt(0);
        char lastInitial = fullName.charAt(spaceIndex + 1);
        System.out.println(firstInitial + "." + lastInitial + ".");
        scanner.close();
    }
}

Expected output: “Alice Johnson” -> A.J.

Common mistakes: Hardcoding the space position instead of using indexOf(" ").


Core 4: Substring Extractor

Show solution
import java.util.Scanner;
public class SubstringExtractor {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        System.out.print("Start index: ");
        int start = scanner.nextInt();
        System.out.print("End index: ");
        int end = scanner.nextInt();
        System.out.println("Substring: " + word.substring(start, end));
        scanner.close();
    }
}

Common mistakes: Expecting end index to be inclusive (it is exclusive).


Extension 5: Word Count

Show solution
import java.util.Scanner;
public class WordCount {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = scanner.nextLine();
        int spaces = 0;
        for (int i = 0; i < sentence.length(); i++) {
            if (sentence.charAt(i) == ' ') {
                spaces++;
            }
        }
        System.out.println("Word count: " + (spaces + 1));
        scanner.close();
    }
}

Common mistakes: Off-by-one: forgetting to add 1 to space count; not handling empty strings.

Marking notes: Accept alternative approaches (split not taught yet, but counting spaces + 1 is expected).


Extension 6: Email Parser

Show solution
import java.util.Scanner;
public class EmailParser {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter email: ");
        String email = scanner.nextLine();
        int atIndex = email.indexOf("@");
        String username = email.substring(0, atIndex);
        String domain = email.substring(atIndex + 1);
        System.out.println("Username: " + username);
        System.out.println("Domain: " + domain);
        scanner.close();
    }
}

Expected output: “alice@school.edu” -> Username: alice, Domain: school.edu

Common mistakes: Off-by-one with substring around the @ symbol.


Extension 7: Palindrome Checker

Show solution
import java.util.Scanner;
public class PalindromeChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        boolean isPalindrome = true;
        for (int i = 0; i < word.length() / 2; i++) {
            if (word.charAt(i) != word.charAt(word.length() - 1 - i)) {
                isPalindrome = false;
            }
        }
        if (isPalindrome) {
            System.out.println(word + " is a palindrome");
        } else {
            System.out.println(word + " is not a palindrome");
        }
        scanner.close();
    }
}

Common mistakes: Comparing wrong indices; forgetting length() - 1 - i; comparing with .equals() instead of charAt() (charAt returns char, use == for char comparison).

Marking notes: Accept break/flag approaches. Using .equals() to compare characters (chars) is incorrect – use == for char.


Challenge 8: Caesar Cipher

Show solution
import java.util.Scanner;
public class CaesarCipher {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word (uppercase): ");
        String word = scanner.nextLine();
        System.out.print("Enter shift: ");
        int shift = scanner.nextInt();
        String result = "";
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            char shifted = (char)('A' + (c - 'A' + shift) % 26);
            result += shifted;
        }
        System.out.println("Encrypted: " + result);
        scanner.close();
    }
}

Common mistakes: Not wrapping around Z (forgetting modulo 26); not handling lowercase/uppercase separately.

Marking notes: Accept uppercase-only solution. Handling both cases is bonus.


Challenge 9: Title Case

Show solution
import java.util.Scanner;
public class TitleCase {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = scanner.nextLine().toLowerCase();
        String result = "";
        boolean capitalizeNext = true;
        for (int i = 0; i < sentence.length(); i++) {
            char c = sentence.charAt(i);
            if (capitalizeNext && c != ' ') {
                result += Character.toUpperCase(c);
                capitalizeNext = false;
            } else {
                result += c;
            }
            if (c == ' ') {
                capitalizeNext = true;
            }
        }
        System.out.println(result);
        scanner.close();
    }
}

Common mistakes: Not lowercasing the input first; capitalize logic off-by-one.

Marking notes: Accept approach using indexOf(" ") and substring to build word-by-word.


Integration Notes

Item In Class Homework Link
Worked Examples 1-2 Walk through together Worked Examples
Quick Code Check MCQs End of Period 1 Quick Code Check
Core #1-4 Period 1 practice Practice Exercises
Extension #5-7 Start in Period 2 Complete for homework Practice Exercises
Challenge #8-9 Optional extension Practice Exercises
Trace Exercise Period 2 wrap-up Trace Exercise
GitHub Classroom Due end of week GitHub Classroom

Additional Resources

  • Live coding walkthrough: demonstrate concatenation, immutability, length, indexOf, substring
  • Password creator activity: combine substring + charAt + concatenation
  • Discussion prompt: “Why is String manipulation important for user-facing solutions?”

Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.