Substring Extraction and Manipulation
Extracting Substrings
substring
A substring is a portion of a string, obtained using an index or slicing operation.
Python:
text = "Hello World"
sub = text[0:5] # "Hello"Java:
String text = "Hello World";
String sub = text.substring(0, 5); // "Hello"Always remember indices start at 0 in most programming languages.
Off-by-one errors when choosing start and end indices.
Concatenating Strings
Joining two or more strings together.
Python:
name = "Data" + "Science" # "DataScience"Java:
String name = "Data" + "Science"; // "DataScience"Concatenation is often used to build dynamic messages or outputs.
Forgetting that + in Python/Java works only for strings, not numbers (without conversion).
Altering Substrings
Changing case, trimming, or modifying parts of a string.
Python:
text = "hello"
altered = text.upper() # "HELLO"Java:
String text = "hello";
String altered = text.toUpperCase(); // "HELLO"Use built-in string methods to avoid unnecessary loops.
Thinking strings are mutable: in both Python and Java, strings are immutable, so you must assign the result to a new variable.
Replacing Substrings
Substituting part of a string with another value.
Python:
text = "I like cats"
new_text = text.replace("cats", "dogs") # "I like dogs"Java:
String text = "I like cats";
String newText = text.replace("cats", "dogs"); // "I like dogs"Useful for text cleaning and data preprocessing.
Assuming replace() changes the original string: it returns a new string.
Searching Within Strings
Finding the position (index) of a substring.
Python:
text = "banana"
pos = text.find("na") # 2Java:
String text = "banana";
int pos = text.indexOf("na"); // 2Trimming and Splitting Strings
Trimming = Removes spaces or characters.
Python:
text = " hi ".strip() # "hi"Java:
String text = " hi ".trim(); // "hi"Splitting = Breaks a string into parts.
Python:
words = "a,b,c".split(",") # ['a', 'b', 'c']Java:
String[] words = "a,b,c".split(","); // ["a", "b", "c"]Splitting is useful for CSV and text parsing.
Forgetting to handle empty strings when trimming or splitting.
In tracing questions, always keep track of how substring operations affect indices and outputs step by step.