Strings
Strings
Learn how strings help programmers store, process, display, search, and manipulate text data in programming languages.
What is a String?
A string is a sequence of characters used to represent text in programming.
A string can contain letters, digits, spaces, symbols, punctuation marks, and special characters.
Examples of strings:
"Hello"
"Programming Mastery"
"Student123"
"Email: student@example.com"
"Price: 500"
Strings are one of the most commonly used data types because most programs need to work with text in some way.
Easy Real-Life Example
String as a Word or Sentence
Think of a string as text typed from a keyboard. A name, sentence, email address, password, message, or paragraph can all be stored as strings.
Name: "Aman"
City: "Kolkata"
Message: "Welcome to Programming Mastery"
Each of these values is textual data, so it can be stored as a string.
Why are Strings Needed?
Strings are needed because programs often need to store and process text-based information.
Strings are Used For
- Storing names of users, students, employees, or products.
- Displaying messages to users.
- Reading input from users.
- Storing email addresses, phone numbers, and IDs.
- Creating reports and formatted output.
- Searching words inside text.
- Replacing or modifying text.
- Validating passwords, usernames, and forms.
- Processing files, logs, and database records.
- Working with web pages, APIs, and data formats.
Characters and Strings
A character is a single symbol, letter, digit, or space.
A string is made by combining multiple characters.
Character: 'A'
String: "Aman"
The string "Aman" is made of four characters:
'A' 'm' 'a' 'n'
Important Terms Related to Strings
| Term | Meaning | Example |
|---|---|---|
| String | A sequence of characters. | "Hello" |
| Character | A single letter, digit, symbol, or space. | 'H' |
| String Literal | A fixed text value written directly in code. | "Welcome" |
| Index | The position of a character inside a string. | 0, 1, 2 |
| Length | Total number of characters in a string. | len("Hello") = 5 |
| Substring | A smaller part of a string. | "gram" from "program" |
| Concatenation | Joining two or more strings. | "Hello" + "World" |
General Syntax of a String
Different programming languages use slightly different syntax, but strings are usually written inside quotes.
studentName = "Riya"
message = "Welcome to Programming"
Some languages allow single quotes, double quotes, or special multi-line string formats.
singleQuoteString = 'Hello'
doubleQuoteString = "Hello"
multiLineString = """
This is a long text
written in multiple lines
"""
String Indexing
Since a string is a sequence of characters, each character has a position called an index.
In most programming languages, indexing starts from 0.
text = "HELLO"
Index: 0 1 2 3 4
Character: H E L L O
To access a character, we use the string name and index.
DISPLAY text[0] // H
DISPLAY text[1] // E
DISPLAY text[4] // O
String Length
String length means the total number of characters in a string.
text = "Hello"
length(text) = 5
Spaces are also counted as characters.
text = "Hello World"
length(text) = 11
Here, the space between Hello and World is also counted.
String Concatenation
Concatenation means joining two or more strings together.
firstName = "Aman"
lastName = "Sharma"
fullName = firstName + " " + lastName
DISPLAY fullName
Expected Output
Aman Sharma
Concatenation is commonly used to build messages dynamically.
name = "Riya"
message = "Hello, " + name + "!"
DISPLAY message
Expected Output
Hello, Riya!
Substring
A substring is a smaller part extracted from a larger string.
text = "Programming"
substring(text, 0, 7) = "Program"
Substrings are useful when we need only a portion of text.
Substrings are Useful For
- Extracting first name from a full name.
- Extracting domain from an email address.
- Extracting area code from a phone number.
- Extracting file extension from a file name.
- Reading a fixed section from formatted data.
Example 1: Display a String
/*
This program stores and displays a string.
*/
ENTRY POINT
DECLARE courseName AS TEXT = "Programming Mastery"
DISPLAY courseName
END ENTRY POINT
Expected Output
Programming Mastery
Example 2: Count Characters in a String
/*
This program finds the length of a string.
*/
ENTRY POINT
DECLARE message AS TEXT = "Hello"
DISPLAY "Length: " + length(message)
END ENTRY POINT
Expected Output
Length: 5
Example 3: Access Characters by Index
/*
This program accesses individual characters from a string.
*/
ENTRY POINT
DECLARE word AS TEXT = "CODE"
DISPLAY word[0]
DISPLAY word[1]
DISPLAY word[2]
DISPLAY word[3]
END ENTRY POINT
Expected Output
C
O
D
E
Example 4: Traverse a String
Strings can be traversed character by character, just like arrays.
/*
This program visits every character in a string.
*/
ENTRY POINT
DECLARE word AS TEXT = "DATA"
FOR index FROM 0 TO length(word) - 1
DISPLAY word[index]
END FOR
END ENTRY POINT
Expected Output
D
A
T
A
Example 5: Concatenate Strings
/*
This program joins strings together.
*/
ENTRY POINT
DECLARE firstName AS TEXT = "Riya"
DECLARE lastName AS TEXT = "Sen"
DECLARE fullName AS TEXT = firstName + " " + lastName
DISPLAY fullName
END ENTRY POINT
Expected Output
Riya Sen
Example 6: Search a Character in a String
/*
This program checks whether a character exists in a string.
*/
ENTRY POINT
DECLARE word AS TEXT = "PROGRAM"
DECLARE target AS CHARACTER = 'G'
DECLARE isFound AS BOOLEAN = false
FOR index FROM 0 TO length(word) - 1
IF word[index] == target THEN
SET isFound = true
BREAK
END IF
END FOR
IF isFound == true THEN
DISPLAY target + " found"
ELSE
DISPLAY target + " not found"
END IF
END ENTRY POINT
Expected Output
G found
Example 7: Count Vowels in a String
/*
This program counts vowels in a string.
*/
ENTRY POINT
DECLARE text AS TEXT = "Education"
DECLARE vowelCount AS INTEGER = 0
FOR index FROM 0 TO length(text) - 1
DECLARE ch AS CHARACTER = lowercase(text[index])
IF ch == 'a' OR ch == 'e' OR ch == 'i' OR ch == 'o' OR ch == 'u' THEN
SET vowelCount = vowelCount + 1
END IF
END FOR
DISPLAY "Vowels: " + vowelCount
END ENTRY POINT
Expected Output
Vowels: 5
Common String Operations
| Operation | Meaning | Example Idea |
|---|---|---|
| Length | Find total number of characters. | length("Hello") = 5 |
| Concatenation | Join strings together. | "Hello" + "World" |
| Indexing | Access a character by position. | text[0] |
| Substring | Extract part of a string. | "Programming" → "Program" |
| Search | Find a character or word inside a string. | Find "@ " in email |
| Replace | Replace one part with another. | "Hi" → "Hello" |
| Trim | Remove extra spaces from beginning or end. | " Riya " → "Riya" |
| Case Conversion | Convert text to uppercase or lowercase. | "hello" → "HELLO" |
| Split | Break string into parts. | "A,B,C" → ["A", "B", "C"] |
| Compare | Check whether two strings are equal or ordered. | "apple" == "apple" |
String Comparison
String comparison means checking whether two strings are the same or different.
text1 = "Hello"
text2 = "Hello"
IF text1 == text2 THEN
DISPLAY "Strings are equal"
END IF
Many programming languages treat uppercase and lowercase letters differently.
"Hello" is not the same as "hello"
String Immutability
In many programming languages, strings are immutable.
Immutable means that once a string is created, its characters cannot be changed directly. Instead, a new string is created.
text = "hello"
New text after change:
"Hello"
The original string is not directly modified. A new string value is created and assigned.
Escape Characters
Sometimes we need to include special characters inside strings, such as quotes, new lines, or tabs.
Escape characters help represent these special characters safely.
| Escape Idea | Purpose | Example Meaning |
|---|---|---|
| New Line | Move text to next line. | Line break in output. |
| Tab | Add horizontal spacing. | Formatted output. |
| Quote Escape | Use quotes inside a string. | "He said \"Hello\"" |
| Backslash Escape | Show a backslash character. | File path or special text. |
Example 8: Basic Input Validation Using Strings
/*
This program checks whether a username is empty.
*/
ENTRY POINT
DECLARE username AS TEXT = "Aman"
IF length(username) == 0 THEN
DISPLAY "Username cannot be empty"
ELSE
DISPLAY "Username accepted"
END IF
END ENTRY POINT
Expected Output
Username accepted
Example 9: Check Email Contains @ Symbol
/*
This program checks whether an email contains @ symbol.
*/
ENTRY POINT
DECLARE email AS TEXT = "student@example.com"
DECLARE hasAtSymbol AS BOOLEAN = false
FOR index FROM 0 TO length(email) - 1
IF email[index] == '@' THEN
SET hasAtSymbol = true
BREAK
END IF
END FOR
IF hasAtSymbol == true THEN
DISPLAY "Valid basic email format"
ELSE
DISPLAY "Invalid email format"
END IF
END ENTRY POINT
Expected Output
Valid basic email format
String vs Character
| Feature | Character | String |
|---|---|---|
| Meaning | Single symbol. | Sequence of characters. |
| Example | 'A' |
"Aman" |
| Length | Usually one character. | Can have zero, one, or many characters. |
| Use Case | Single letter or symbol. | Names, messages, paragraphs, emails. |
String vs Number
A number written inside quotes becomes a string, not a numeric value.
ageNumber = 25
ageString = "25"
ageNumber can be used in mathematical calculations. ageString is text and may need conversion before calculation.
25 + 5 → 30
"25" + "5" → "255"
Common Beginner Mistakes
Mistakes
- Forgetting to put text inside quotes.
- Confusing numbers with numeric strings.
- Thinking string indexing starts from
1instead of0. - Accessing an index outside the string length.
- Forgetting that spaces are counted as characters.
- Assuming string comparison is always case-insensitive.
- Trying to directly modify immutable strings.
- Forgetting to trim user input before validation.
- Using too much concatenation when formatting would be clearer.
- Not handling empty strings.
Better Habits
- Always use quotes for text values.
- Convert strings to numbers before numeric calculations.
- Remember that indexing usually starts from
0. - Check string length before accessing characters.
- Use trim before validating user input.
- Convert strings to the same case before comparison when needed.
- Create new strings instead of expecting direct modification.
- Use meaningful variable names such as
fullName,message, andemail. - Test with empty strings, spaces, uppercase, lowercase, and special characters.
- Use built-in string functions when available.
Best Practices for Strings
Recommended Practices
- Use strings for text-based data.
- Use meaningful variable names for string values.
- Trim user input before checking it.
- Normalize case before comparing user-entered text.
- Check length before accessing characters by index.
- Use concatenation carefully and keep messages readable.
- Use substring only with valid start and end indexes.
- Handle empty strings properly.
- Be careful with passwords and sensitive text data.
- Use built-in string methods instead of writing unnecessary manual logic.
Prerequisites Before Learning Strings
Students should already understand:
Required Knowledge
- Variables and constants.
- Data types.
- Input and output.
- Operators.
- Conditions.
- Loops and iteration.
- Arrays and indexing basics.
- Functions and methods basics.
Trace Table Example
Let us trace the traversal of the string "CAT".
word = "CAT"
FOR index FROM 0 TO length(word) - 1
DISPLAY word[index]
END FOR
| Iteration | index | word[index] | Output |
|---|---|---|---|
| 1 | 0 |
C |
C |
| 2 | 1 |
A |
A |
| 3 | 2 |
T |
T |
Practice Activity: Identify String Details
Study the following string:
text = "Hello"
Questions
1. What is the length of the string?
2. What character is at index 0?
3. What character is at index 1?
4. What character is at index 4?
5. Is "Hello" the same as "hello"?
Sample Answers
1. Length = 5
2. Index 0 = H
3. Index 1 = e
4. Index 4 = o
5. No, because string comparison is usually case-sensitive.
Mini Quiz
What is a string?
A string is a sequence of characters used to represent text.
What is string length?
String length is the total number of characters in a string.
What is string concatenation?
String concatenation is the process of joining two or more strings together.
What is a substring?
A substring is a smaller part extracted from a larger string.
Why are strings important?
Strings are important because they allow programs to store, display, process, and validate text data.
Interview Questions on Strings
Define string in programming.
A string is a data type or structure used to store a sequence of characters.
What is the difference between a character and a string?
A character is a single symbol, while a string is a sequence of characters.
What is string indexing?
String indexing is accessing characters in a string using their position numbers.
What does immutable string mean?
An immutable string cannot be changed directly after creation; modifications create a new string.
Give examples of common string operations.
Common string operations include length, concatenation, substring, search, replace, trim, split, and case conversion.
Quick Summary
| Concept | Meaning |
|---|---|
| String | A sequence of characters used to store text. |
| Character | A single letter, digit, symbol, or space. |
| Index | The position of a character in a string. |
| Length | Total number of characters in a string. |
| Concatenation | Joining strings together. |
| Substring | A smaller part of a string. |
| Comparison | Checking whether strings are equal or ordered. |
| Best Use | Names, messages, emails, passwords, files, logs, and user input. |
Final Takeaway
Strings are essential for working with text in programming. They allow programs to store names, messages, emails, passwords, user input, and many other text values. In the Programming Mastery Course, students should understand strings as sequences of characters that can be indexed, measured, joined, searched, compared, and processed using common string operations.