Skip to content
beginnerPhase 10 · Java Arrays & Strings

String Methods

Master essential String methods: charAt, substring, indexOf, split, toCharArray, and more.

45m
3 problems
Topic Progress0%

Character Methods

Character Access and Inspection

charAt() Method

String str = "Hello World";

// Access character at index
char first = str.charAt(0);   // 'H'
char last = str.charAt(10);    // 'd'

// Iterate through characters
for (int i = 0; i < str.length(); i++) {
    System.out.println(str.charAt(i));
}

// Enhanced for loop
for (char c : str.toCharArray()) {
    System.out.println(c);
}

toCharArray() Method

String str = "Hello";
char[] chars = str.toCharArray();

// Now you can use array operations
Arrays.sort(chars);  // ['e', 'H', 'l', 'l', 'o']

// Convert back to String
String sorted = new String(chars);  // "eHllo"

Character Class Methods

char c = 'A';

// Check character type
boolean isLetter = Character.isLetter(c);      // true
boolean isDigit = Character.isDigit(c);        // false
boolean isLetterOrDigit = Character.isLetterOrDigit(c);  // true
boolean isUpperCase = Character.isUpperCase(c); // true
boolean isLowerCase = Character.isLowerCase(c); // false
boolean isWhitespace = Character.isWhitespace(c); // false

// Convert case
char lower = Character.toLowerCase(c);  // 'a'
char upper = Character.toUpperCase('a');  // 'A'

// Get numeric value
int digit = Character.getNumericValue('5');  // 5

Practical Examples

// Count vowels
public int countVowels(String str) {
    int count = 0;
    for (char c : str.toLowerCase().toCharArray()) {
        if ("aeiou".indexOf(c) != -1) {
            count++;
        }
    }
    return count;
}

// Check if string is palindrome
public boolean isPalindrome(String str) {
    int left = 0, right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// Reverse string
public String reverse(String str) {
    char[] chars = str.toCharArray();
    int left = 0, right = chars.length - 1;
    while (left < right) {
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

Search Methods

String Search Operations

indexOf() and lastIndexOf()

String str = "Hello World";

// Find first occurrence
int firstL = str.indexOf('l');         // 2
int firstO = str.indexOf('o');         // 4

// Find last occurrence
int lastL = str.lastIndexOf('l');      // 9
int lastO = str.lastIndexOf('o');      // 7

// Find substring
int worldIdx = str.indexOf("World");  // 6

// Find from specific index
int secondL = str.indexOf('l', 3);    // 3 (starts searching from index 3)

// Not found
int notFound = str.indexOf("xyz");    // -1

contains() Method

String str = "Hello World";

boolean hasHello = str.contains("Hello");  // true
boolean hasWorld = str.contains("world");  // false (case-sensitive)
boolean hasEmpty = str.contains("");       // true

// Practical use
if (str.contains("@")) {
    System.out.println("Valid email format");
}

startsWith() and endsWith()

String filename = "document.pdf";

boolean startsWithDoc = filename.startsWith("doc");   // true
boolean endsWithPdf = filename.endsWith(".pdf");      // true

// With offset
boolean startsWithO = filename.startsWith("oc", 2);   // true

// Practical use
if (filename.endsWith(".pdf")) {
    openPDF(filename);
} else if (filename.endsWith(".docx")) {
    openWord(filename);
}

matches() Method

String email = "user@example.com";

// Check if matches regex pattern
boolean isEmail = email.matches("^[\\\w.-]+@[\\\w.-]+\\\.[a-zA-Z]{2,}$");

String phone = "+1-234-567-8900";
boolean isPhone = phone.matches("\\\+?\\\d{1,3}-?\\\d{3}-?\\\d{3}-?\\\d{4}");

// Simple pattern matching
String alphanumeric = "abc123";
boolean isAlnum = alphanumeric.matches("[a-zA-Z0-9]+");

Region Matches

String str = "Hello World";

// Check if region matches
boolean match = str.regionMatches(6, "World", 0, 5);  // true

// Case-insensitive
boolean match2 = str.regionMatches(true, 6, "WORLD", 0, 5);  // true

Practical Examples

// Find all occurrences of a character
public List<Integer> findAllOccurrences(String str, char target) {
    List<Integer> indices = new ArrayList<>();
    int index = str.indexOf(target);
    while (index != -1) {
        indices.add(index);
        index = str.indexOf(target, index + 1);
    }
    return indices;
}

// Check if string contains only digits
public boolean isNumeric(String str) {
    for (char c : str.toCharArray()) {
        if (!Character.isDigit(c)) {
            return false;
        }
    }
    return true;
}

Transform Methods

String Transformation

Case Transformation

String str = "Hello World";

String upper = str.toUpperCase();    // "HELLO WORLD"
String lower = str.toLowerCase();    // "hello world"

// Note: These create new strings
// Original str is unchanged
System.out.println(str);  // "Hello World"

trim() and strip()

String padded = "   Hello   ";

// trim() - removes leading/trailing whitespace
String trimmed = padded.trim();  // "Hello"

// strip() - Java 11+, handles Unicode whitespace
String stripped = padded.strip();  // "Hello"
String strippedLeading = padded.stripLeading();   // "Hello   "
String strippedTrailing = padded.stripTrailing(); // "   Hello"

// Check if empty after trimming
if (str.trim().isEmpty()) {
    System.out.println("String is empty or whitespace");
}

replace() and replaceAll()

String str = "Hello World";

// Replace character
String replaced = str.replace('l', 'L');  // "HeLLo WorLd"

// Replace substring
String replaced2 = str.replace("World", "Java");  // "Hello Java"

// ReplaceAll (regex)
String cleaned = str.replaceAll("[^a-zA-Z]", "");  // "HelloWorld"

// Replace first occurrence only
String replaced3 = str.replaceFirst("l", "L");  // "HeLlo World"

// Practical: Remove all digits
String withDigits = "abc123def456";
String noDigits = withDigits.replaceAll("\\\d", "");  // "abcdef"

substring() (Review)

String str = "Hello World";

// From index to end
String sub1 = str.substring(6);      // "World"

// From index to index (exclusive)
String sub2 = str.substring(0, 5);   // "Hello"

// Empty string
String sub3 = str.substring(5, 5);   // ""

Practical Examples

// Capitalize first letter
public String capitalize(String str) {
    if (str.isEmpty()) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}

// Convert to camelCase
public String toCamelCase(String str) {
    StringBuilder sb = new StringBuilder();
    boolean capitalizeNext = false;
    for (char c : str.toCharArray()) {
        if (c == ' ' || c == '_') {
            capitalizeNext = true;
        } else if (capitalizeNext) {
            sb.append(Character.toUpperCase(c));
            capitalizeNext = false;
        } else {
            sb.append(Character.toLowerCase(c));
        }
    }
    return sb.toString();
}

// Truncate string
public String truncate(String str, int maxLength) {
    if (str.length() <= maxLength) return str;
    return str.substring(0, maxLength - 3) + "...";
}

Conversion

String Conversion Methods

String to Other Types

// To int
int num = Integer.parseInt("123");

// To double
double dbl = Double.parseDouble("3.14");

// To long
long big = Long.parseLong("1234567890");

// To boolean
boolean flag = Boolean.parseBoolean("true");  // true
boolean flag2 = Boolean.parseBoolean("yes");  // false

// To char array
char[] chars = "Hello".toCharArray();

Other Types to String

// From int
String fromInt = String.valueOf(123);     // "123"
String fromInt2 = Integer.toString(123);  // "123"
String fromInt3 = 123 + "";               // "123"

// From double
String fromDbl = String.valueOf(3.14);    // "3.14"
String fromDbl2 = Double.toString(3.14);  // "3.14"

// From boolean
String fromBool = String.valueOf(true);    // "true"

// From char array
String fromChars = new String(new char[]{'H', 'e', 'l', 'l', 'o'});  // "Hello"
String fromChars2 = new String(new char[]{'H', 'e', 'l', 'l', 'o'}, 1, 3);  // "ell"

String.format()

// Basic formatting
String name = "Alice";
int age = 25;
String msg = String.format("Name: %s, Age: %d", name, age);

// Format specifiers
String formatted = String.format(
    "Int: %d, Float: %.2f, Char: %c, String: %s, Bool: %b",
    42, 3.14159, 'A', "hello", true
);

// Width and alignment
String padded = String.format("%10s", "hello");    // "     hello"
String leftPad = String.format("%-10s", "hello");  // "hello     "

// Zero padding
String zeroPadded = String.format("%05d", 42);  // "00042"

StringBuilder Conversion

// StringBuilder to String
StringBuilder sb = new StringBuilder("Hello");
String str = sb.toString();

// String to StringBuilder
String str = "Hello";
StringBuilder sb = new StringBuilder(str);

// Append and convert
String result = new StringBuilder()
    .append("Hello")
    .append(" ")
    .append("World")
    .toString();

Practical Examples

// Join array elements
String[] arr = {"a", "b", "c"};
String joined = String.join(", ", arr);  // "a, b, c"

// Parse CSV line
String csv = "John,Doe,30,New York";
String[] parts = csv.split(",");
// ["John", "Doe", "30", "New York"]

// Format currency
double price = 19.99;
String formatted = String.format("$%.2f", price);  // "$19.99"

// Format date
String date = String.format("%tF", new Date());  // "2024-01-15"

Practice Problems

0/3solved
Valid Palindrome
Two Pointers

Given a string s, return true if it is a palindrome considering only alphanumeric characters.

Example:

Input: s = "A man, a plan, a canal: Panama"

Output: true

"amanaplanacanalpanama" is a palindrome

Optimal Solution — O(n) time, O(1) space

Two pointers after filtering non-alphanumeric characters.

public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
        while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
        if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Edge Cases:

  • Empty string
  • Single character
  • All non-alphanumeric
Longest Common Prefix
String Comparison

Find the longest common prefix string among an array of strings.

Example:

Input: strs = ["flower","flow","flight"]

Output: "fl"

The longest common prefix is "fl"

Optimal Solution — O(S) time, O(1) space

Compare characters at each position.

public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }
    }
    return prefix;
}

Edge Cases:

  • Empty array
  • Single string
  • No common prefix
Group Anagrams
HashMap

Group strings that are anagrams of each other.

Example:

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Group by sorted character

Optimal Solution — O(n * k log k) time, O(n * k) space

Use sorted string as key in HashMap.

public List<List<String>> groupAnagrams(String[] strs) {
    Map<String, List<String>> map = new HashMap<>();
    for (String s : strs) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        String key = new String(chars);
        map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
    }
    return new ArrayList<>(map.values());
}

Edge Cases:

  • Empty array
  • Single string
  • No anagrams

Quiz

1. What does str.trim() do?

Question 1 options

2. What does indexOf() return if the substring is not found?

Question 2 options

3. How do you convert a string to lowercase?

Question 3 options

4. What is the difference between replace() and replaceAll()?

Question 4 options

Flashcards

Question

How do you check if a string contains a substring?

Answer

Use contains(): str.contains("substring") returns true/false.

Question

How do you split a string by delimiter?

Answer

Use split(): str.split(",") returns String array.

Question

How do you join an array of strings?

Answer

Use String.join(): String.join(", ", array) returns joined string.

Question

What does toCharArray() do?

Answer

Converts the string to a character array. Useful for sorting or modifying individual characters.

Question

What is String Methods?

Answer

String Methods is a key concept in Java programming.

Revision Notes

Key Takeaways

  • 1.String methods return new strings (immutability)
  • 2.indexOf() returns -1 when not found
  • 3.replaceAll() uses regex, replace() uses literal
  • 4.Use trim() to remove whitespace

Interview Tips

  • Practice string manipulation problems
  • Know common methods: charAt, indexOf, substring, split
  • Remember strings are immutable
  • Use StringBuilder for multiple modifications

Cheat Sheet

Cheat Sheet

  • Length: str.length()
  • Access: str.charAt(index)
  • Search: str.indexOf(str), str.contains(str)
  • Check: str.startsWith(str), str.endsWith(str)
  • Transform: str.toUpperCase(), str.toLowerCase(), str.trim()
  • Replace: str.replace(old, new), str.replaceAll(regex, new)
  • Split: str.split(delimiter)
  • Join: String.join(delimiter, elements)
  • Substring: str.substring(start, end)
  • Format: String.format(pattern, args)