Substrings
What Is a Substring?
A substring is a smaller sequence of characters extracted from a larger string.
Common operations involving substrings include extraction, alteration, concatenation, and replacement.
Common Substring Operations
| Operation | Description |
|---|---|
| Extracting Substrings | Getting part of a string using start and end positions. |
| Altering Substrings | Changing characters in a substring. |
| Concatenating Strings | Joining two or more strings together. |
| Replacing Substrings | Replacing specific substrings within a string. |
Extracting and Manipulating Substrings
Switch between Python and Java below to see a handful of functions and methods to manipulate a sentence, and print the results.
text = "Welcome to IB Computer Science"
# Extract "IB Computer"
substring = text[11:22]
# Replace "Computer" → "System" (in the extracted piece)
altered_substring = substring.replace("Computer", "System")
# Concatenate the extracted piece with " Science"
concatenated = substring + " Science"
# Replace "Science" → "Engineering" (in the full text)
replaced_text = text.replace("Science", "Engineering")
print("Extracted:", substring)
print("Altered:", altered_substring)
print("Concatenated:", concatenated)
print("Replaced:", replaced_text)
public class SubstringExample {
public static void main(String[] args) {
String text = "Welcome to IB Computer Science";
// Extract "IB Computer"
String substring = text.substring(11, 22);
// Replace "Computer" → "System" (in the extracted piece)
String alteredSubstring = substring.replace("Computer", "System");
// Concatenate the extracted piece with " Science"
String concatenated = substring + " Science";
// Replace "Science" → "Engineering" (in the full text)
String replacedText = text.replace("Science", "Engineering");
System.out.println("Extracted: " + substring);
System.out.println("Altered: " + alteredSubstring);
System.out.println("Concatenated: " + concatenated);
System.out.println("Replaced: " + replacedText);
}
}
String Function Reference
A quick, practical catalogue of common string operations in Python and Java. Each row shows the function, what it does, and a short, copiable snippet.
| Function / Feature | Description | Sample code |
|---|---|---|
len(s) |
Length (number of characters). |
|
| Index / Slice | Access a character or a slice (substring). |
|
| Containment | Check if one string occurs in another. |
|
.lower(), .upper(), .title() |
Case conversions (lowercase, UPPERCASE, Title Case). |
|
.strip(), .lstrip(), .rstrip() |
Trim whitespace (or given chars) from ends. |
|
.startswith(), .endswith() |
Prefix / suffix checks. |
|
.find(), .rfind() |
First/last index of a substring (or -1 if absent). |
|
.replace(old, new) |
Replace all occurrences of a substring. |
|
.split(), .rsplit(), .splitlines() |
Split by delimiter / from right / by line breaks. |
|
sep.join(iterable) |
Join pieces with a separator. |
|
.partition(sep), .rpartition(sep) |
Split once into (before, sep, after). |
|
.count(sub) |
Occurrences of a substring. |
|
| "is" tests | Character-type checks (digit, alpha, etc.). |
|
| Formatting | Build strings with values (f-strings / .format). |
|
.removeprefix(), .removesuffix() |
Drop a fixed prefix/suffix (Py 3.9+). |
|
| Padding / Align | Left/right justify, center, zero-fill. |
|
| Translate | Character mapping with str.maketrans. |
|
| Regex Match | Pattern matching for validation and extraction. |
|
| Method | Description | Sample code |
|---|---|---|
length() |
Length (number of chars). |
|
charAt(i) |
Character at index. |
|
substring(a,b) |
Slice from a (incl) to b (excl). |
|
contains(seq) |
Whether it includes a sequence. |
|
indexOf(), lastIndexOf() |
First/last position of substring (or -1). |
|
startsWith(), endsWith() |
Prefix / suffix checks. |
|
toLowerCase(), toUpperCase() |
Case conversion. |
|
trim() / strip() (JDK 11) |
Remove surrounding whitespace. |
|
replace() / replaceAll() |
Literal or regex-based replacement. |
|
split(regex) |
Split into parts by delimiter/regex. |
|
String.join() |
Join with a delimiter. |
|
| Equality | Compare strings (case-sensitive/insensitive). |
|
| Empty / Blank (JDK 11) | isEmpty(): length==0; isBlank(): empty or whitespace. |
|
| Formatting | Build strings from values. |
|
| Repeat (JDK 11) | Repeat a string N times. |
|
| Regex match | Full-string regex check. |
|
| Compare | Lexicographic compare (<0, =0, >0). |
|
| Concatenate | Join strings with + or use StringBuilder in loops. |
|
Challenges in Handling Substrings
- Index Errors: Extracting substrings using incorrect indices can cause out-of-range errors.
- Immutability: Strings in languages like Java and Python are immutable, requiring reassignment after modifications.
- Case Sensitivity: Searching and replacing substrings require careful handling of case variations.
Key Takeaways
- Substrings are smaller parts extracted from larger strings.
- Operations include extraction, alteration, concatenation, and replacement.
- Accurate indexing is essential to prevent errors when working with substrings.
- Python and Java both offer built-in methods to extract and manipulate substrings effectively.