1.07

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
Prerequisites: [object Object]
Estimated Time: 55 min

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.

plaintext
String: "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

java
public 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

python
name = "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

java
String name = "Alice"; System.out.println(name.length()); // 5

Accessing Characters

Use the index to get a single character from a string.

Python

python
text = "Hello" print(text[0]) # H print(text[1]) # e print(text[4]) # o print(text[-1]) # o (last character)

C

c
char text[] = "Hello"; printf("%c\n", text[0]); // H printf("%c\n", text[4]); // o

Java

java
String 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

python
text = "Hello" for char in text: print(char) # Or with index: for i in range(len(text)): print(text[i])

C

c
char text[] = "Hello"; for (int i = 0; text[i] != '\0'; i++) { printf("%c\n", text[i]); }

Java

java
String text = "Hello"; for (int i = 0; i < text.length(); i++) { System.out.println(text.charAt(i)); }

Substrings

Extract a portion of a string.

Python

python
text = "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

java
String 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

python
first = "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

java
String 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:

python
text = "Programming" reversed_text = text[::-1] print(reversed_text) # "gnimmargorP" # Or manually: result = "" for char in text: result = char + result print(result) # "gnimmargorP"

Java:

java
String 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:

python
text = "Programming" count = 0 search_char = 'r' for char in text: if char == search_char: count = count + 1 print(count) # 2

Java:

java
String 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:

python
text = "racecar" is_palindrome = text == text[::-1] print(is_palindrome) # true

Java:

java
String 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

python
text = "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), or strlen() (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