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, practi­cal 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).
s = "Hello"
print(len(s))  # 5
Index / Slice Access a character or a slice (sub­string).
s = "computer"
first = s[0]      # 'c'
last  = s[-1]     # 'r'
part  = s[2:5]    # 'mpu'
Containment Check if one string occurs in another.
"cat" in "concatenate"   # True
"dog" in "concatenate"   # False
.lower(), .upper(), .title() Case conversions (lowercase, UPPERCASE, Title Case).
s = "hello world"
print(s.upper())   # HELLO WORLD
print(s.title())   # Hello World
.strip(), .lstrip(), .rstrip() Trim whitespace (or given chars) from ends.
s = "  data  "
print(s.strip())   # "data"
.startswith(), .endswith() Prefix / suffix checks.
path = "/home/user/file.txt"
print(path.endswith(".txt"))  # True
.find(), .rfind() First/last index of a substring (or -1 if absent).
s = "balloon"
print(s.find("lo"))   # 3
print(s.rfind("l"))   # 3
.replace(old, new) Replace all occurrences of a substring.
"cat cat".replace("cat", "dog")  # "dog dog"
.split(), .rsplit(), .splitlines() Split by delimiter / from right / by line breaks.
"a,b,c".split(",")   # ["a","b","c"]
"a\nb".splitlines()   # ["a","b"]
sep.join(iterable) Join pieces with a separator.
names = ["Ada","Grace","Lin"]
print(", ".join(names))
.partition(sep), .rpartition(sep) Split once into (before, sep, after).
"key=value".partition("=")
# ("key","=","value")
.count(sub) Occurrences of a substring.
print("hello".count("l"))  # 2
                                        
"is" tests Character-type checks (digit, alpha, etc.).
"123".isdigit()   # True
"abc".isalpha()   # True
"abc1".isalnum()  # True
Formatting Build strings with values (f-strings / .format).
name, n = "Alex", 3
print(f"{name} has {n} points")
print("{} has {} points".format(name, n))
.removeprefix(), .removesuffix() Drop a fixed prefix/suffix (Py 3.9+).
p = "/home/user/file.txt"
print(p.removeprefix("/home/"))
Padding / Align Left/right justify, center, zero-fill.
print("7".zfill(3))        # "007"
print("hi".center(6,"-"))  # "--hi--"
Translate Character mapping with str.maketrans.
s = "replace ae"
tbl = str.maketrans({"a":"@", "e":"3"})
print(s.translate(tbl))
Regex Match Pattern matching for validation and extraction.
import re
email = "[email protected]"
if re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
    print("Valid email")  # "Valid email"
Method Description Sample code
length() Length (number of chars).
String s = "Hello";
System.out.println(s.length()); // 5
charAt(i) Character at index.
String s = "abc";
char c = s.charAt(1); // 'b'
substring(a,b) Slice from a (incl) to b (excl).
String s = "computer";
System.out.println(s.substring(2,5)); // "mpu"
contains(seq) Whether it includes a sequence.
String s = "concatenate";
System.out.println(s.contains("cat")); // true
indexOf(), lastIndexOf() First/last position of substring (or -1).
String s = "balloon";
System.out.println(s.indexOf("lo"));   // 3
System.out.println(s.lastIndexOf("l"));// 3
startsWith(), endsWith() Prefix / suffix checks.
String p = "/home/user/file.txt";
System.out.println(p.endsWith(".txt")); // true
toLowerCase(), toUpperCase() Case conversion.
String s = "Hello World";
System.out.println(s.toLowerCase());
trim() / strip() (JDK 11) Remove surrounding whitespace.
String s = "  data  ";
System.out.println(s.trim());
replace() / replaceAll() Literal or regex-based replacement.
String s = "cat cat";
System.out.println(s.replace("cat","dog"));   // literal
// s.replaceAll("\s+"," ")  // regex
split(regex) Split into parts by delimiter/regex.
String csv = "a,b,c";
String[] parts = csv.split(",");
String.join() Join with a delimiter.
List<String> names = List.of("Ada","Grace","Lin");
System.out.println(String.join(", ", names));
Equality Compare strings (case-sensitive/insensitive).
String a="Hi", b="hi";
a.equals(b);            // false
a.equalsIgnoreCase(b);  // true
Empty / Blank (JDK 11) isEmpty(): length==0; isBlank(): empty or whitespace.
"".isEmpty();     // true
"  ".isBlank();   // true
Formatting Build strings from values.
String out = String.format("%s has %d points", "Alex", 3);
System.out.println(out);
Repeat (JDK 11) Repeat a string N times.
System.out.println("-".repeat(5)); // -----
Regex match Full-string regex check.
String s = "123-45";
System.out.println(s.matches("\d{3}-\d{2}"));
Compare Lexicographic compare (<0, =0, >0).
"apple".compareTo("banana"); // < 0
Concatenate Join strings with + or use StringBuilder in loops.
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World");
System.out.println(sb.toString());

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.