Strings
Learn to work with strings and text. Manipulate characters, access substrings, and perform string operations.
Learning Objectives:
- β’Understand strings as sequences of characters
- β’Find the length of a string
- β’Access individual characters by index
- β’Extract substrings
- β’Concatenate strings
- β’Iterate through string characters
Strings
What is a String?
A string is a sequence of characters. Like arrays, strings use indexing, where each character has a position starting at 0.
plaintextString: "Hello" Index: 0 1 2 3 4 H e l l o
Strings are everywhere in programming:
- User names ("Alice")
- Messages ("Welcome!")
- File paths ("/home/user/file.txt")
Creating Strings
Python
python# Simple string name = "Alice" # String with spaces message = "Hello, World!" # Empty string empty = "" # String with numbers (still text) zip_code = "12345"
C
c#include <stdio.h> int main() { // C strings are arrays of characters, ending with '\0' char name[50] = "Alice"; char message[50] = "Hello, World!"; return 0; }
Java
javapublic class Main { public static void main(String[] args) { String name = "Alice"; String message = "Hello, World!"; String empty = ""; } }
String Length
Every string has a length β the number of characters it contains.
Python
pythonname = "Alice" print(len(name)) # 5 message = "Hello, World!" print(len(message)) # 13
C
c#include <stdio.h> #include <string.h> int main() { char name[50] = "Alice"; printf("%lu\n", strlen(name)); // 5 return 0; }
Java
javaString name = "Alice"; System.out.println(name.length()); // 5
Accessing Characters
Use the index to get a single character from a string.
Python
pythontext = "Hello" print(text[0]) # H print(text[1]) # e print(text[4]) # o print(text[-1]) # o (last character)
C
cchar text[] = "Hello"; printf("%c\n", text[0]); // H printf("%c\n", text[4]); // o
Java
javaString text = "Hello"; System.out.println(text.charAt(0)); // H System.out.println(text.charAt(4)); // o
Iterating Through Strings
You can loop through every character in a string.
Python
pythontext = "Hello" for char in text: print(char) # Or with index: for i in range(len(text)): print(text[i])
C
cchar text[] = "Hello"; for (int i = 0; text[i] != '\0'; i++) { printf("%c\n", text[i]); }
Java
javaString text = "Hello"; for (int i = 0; i < text.length(); i++) { System.out.println(text.charAt(i)); }
Substrings
Extract a portion of a string.
Python
pythontext = "Programming" print(text[0:4]) # "Prog" (from index 0 to 3) print(text[3:7]) # "gram" (from index 3 to 6) print(text[5:]) # "amming" (from index 5 to end) print(text[:3]) # "Pro" (from start to index 2)
C
c#include <stdio.h> #include <string.h> int main() { char text[] = "Programming"; char sub[20]; // Copy substring: strncpy(destination, source, length) strncpy(sub, &text[0], 4); sub[4] = '\0'; // null-terminate printf("%s\n", sub); // "Prog" return 0; }
Java
javaString text = "Programming"; System.out.println(text.substring(0, 4)); // "Prog" System.out.println(text.substring(3, 7)); // "gram" System.out.println(text.substring(5)); // "amming"
Concatenation
Combine two strings together.
Python
pythonfirst = "Hello" second = "World" result = first + " " + second print(result) # "Hello World"
C
c#include <stdio.h> #include <string.h> int main() { char first[50] = "Hello"; char second[50] = "World"; char result[100]; // Use strcat to concatenate strcpy(result, first); strcat(result, " "); strcat(result, second); printf("%s\n", result); // "Hello World" return 0; }
Java
javaString first = "Hello"; String second = "World"; String result = first + " " + second; System.out.println(result); // "Hello World"
Real-World Example: Reverse a String
Problem: Read a string and print it backward.
Python:
pythontext = "Programming" reversed_text = text[::-1] print(reversed_text) # "gnimmargorP" # Or manually: result = "" for char in text: result = char + result print(result) # "gnimmargorP"
Java:
javaString text = "Programming"; String reversed = new StringBuilder(text).reverse().toString(); System.out.println(reversed); // "gnimmargorP"
Counting Characters
Problem: Count how many times a character appears in a string.
Python:
pythontext = "Programming" count = 0 search_char = 'r' for char in text: if char == search_char: count = count + 1 print(count) # 2
Java:
javaString text = "Programming"; char search_char = 'r'; int count = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == search_char) { count = count + 1; } } System.out.println(count); // 2
Checking for Palindromes
Problem: Check if a string reads the same forwards and backwards.
Python:
pythontext = "racecar" is_palindrome = text == text[::-1] print(is_palindrome) # true
Java:
javaString text = "racecar"; String reversed = new StringBuilder(text).reverse().toString(); boolean is_palindrome = text.equals(reversed); System.out.println(is_palindrome); // true
Common String Pitfalls
Be careful with string comparison
Python:
python# Correct if text == "hello": print("Match!") # Note: != works for inequality if text != "hello": print("No match")
Java:
java// Correct - use .equals() if (text.equals("hello")) { System.out.println("Match!"); } // WRONG - don't use == // if (text == "hello") // This checks memory location, not content
String indices are 0-based
pythontext = "Hello" text[0] # 'H' (first character) text[5] # ERROR - index out of bounds
Key Takeaways
- Strings are sequences of characters, indexed from 0
- Length is found using
len()(Python),.length()(Java), orstrlen()(C) - Characters are accessed by index:
text[i] - Substrings are extracted using slicing syntax
- Concatenation combines strings:
str1 + str2 - Loops let you iterate through every character
- Palindromes read the same forwards and backwards
Summary
Strings are fundamental in programming. With string manipulation techniques, you can process text data, search for patterns, and build interactive programs that work with user input.
Progress: 7/8 chapters complete in Level 1
Exercises
Exercise 1: String Length
Read a string and determine its length.
Exercise 2: Reverse a String
Display the characters of a string in reverse order.
Exercise 3: Count Vowels
Count the vowels in the provided text.
Exercise 4: Palindrome
Determine whether the provided text is a palindrome.
Exercise 5: Count a Character
Count how many times the requested character appears in a string.
Exercise 6: String Compression
Compress repeated characters in a string using the format required by the exercise.