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.
Common MistakeOff-by-one errors when choosing start and end indices.
Concatenating Strings
Joining two or more strings together.Example
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.Example
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.