Common String Operations
Common String Operations
Learn the most important string operations used to inspect, combine, search, extract, replace, clean, and transform text data.
What are Common String Operations?
Common string operations are actions performed on strings to read, modify, analyze, compare, or transform text data.
Since strings are used to store text such as names, messages, emails, passwords, addresses, and user input, programmers frequently perform different operations on strings.
Example string:
text = " Programming Mastery "
We can perform many operations on this string, such as finding its length, trimming spaces, converting it to uppercase, or extracting a part of it.
Easy Real-Life Example
String Operations as Editing Text
Imagine you are editing a sentence in a document. You may count letters, remove extra spaces, replace a word, make text uppercase, or split a sentence into words.
Programming string operations work in a similar way. They allow us to process text automatically inside programs.
Original Text: " hello world "
After trim: "hello world"
After uppercase: "HELLO WORLD"
After replace: "hello programming"
Why are String Operations Needed?
String operations are needed because raw text is often not ready to use directly. It may contain extra spaces, wrong letter case, missing parts, unwanted characters, or multiple values combined together.
String Operations are Used For
- Validating names, emails, passwords, and usernames.
- Cleaning user input before storing it.
- Combining first name and last name.
- Extracting parts of text such as domain name from email.
- Searching whether a word exists in a sentence.
- Replacing old text with new text.
- Splitting comma-separated values into separate items.
- Converting text to uppercase or lowercase.
- Comparing two strings.
- Formatting messages for output.
List of Common String Operations
| Operation | Purpose | Example Idea |
|---|---|---|
| Length | Counts total characters in a string. | length("Hello") = 5 |
| Indexing | Accesses a character using its position. | text[0] |
| Traversal | Visits each character one by one. | Loop through all characters. |
| Concatenation | Joins two or more strings. | "Hello" + "World" |
| Substring | Extracts a part of a string. | "Programming" → "Program" |
| Search / Find | Finds a character or word inside text. | Find "@" in email. |
| Replace | Replaces old text with new text. | "Hi" → "Hello" |
| Trim | Removes extra spaces from beginning and end. | " Aman " → "Aman" |
| Case Conversion | Changes text to uppercase or lowercase. | "hello" → "HELLO" |
| Split | Breaks a string into multiple parts. | "A,B,C" → ["A", "B", "C"] |
| Join | Combines multiple string items into one string. | ["A","B"] → "A,B" |
| Compare | Checks whether two strings are equal or ordered. | "apple" == "apple" |
1. Length Operation
The length operation finds the total number of characters in a string.
Letters, digits, symbols, and spaces are counted as characters.
text = "Hello"
length(text) = 5
If the string contains a space, the space is also counted.
text = "Hello World"
length(text) = 11
Example: Find String Length
/*
This program finds the length of a string.
*/
ENTRY POINT
DECLARE message AS TEXT = "Programming"
DISPLAY "Length: " + length(message)
END ENTRY POINT
Expected Output
Length: 11
2. Indexing Operation
Indexing means accessing a character from a string using its position number.
In most programming languages, string indexing starts from 0.
text = "CODE"
Index: 0 1 2 3
Character: C O D E
Example: Access Characters
/*
This program accesses characters using indexes.
*/
ENTRY POINT
DECLARE word AS TEXT = "CODE"
DISPLAY word[0]
DISPLAY word[2]
END ENTRY POINT
Expected Output
C
D
n characters, the last valid index is usually n - 1.
3. String Traversal
String traversal means visiting every character in a string one by one.
Traversal is useful for counting characters, searching letters, checking vowels, validating input, or processing text.
word = "DATA"
Traversal:
D → A → T → A
Example: Traverse a String
/*
This program traverses a string character by character.
*/
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
4. Concatenation Operation
Concatenation means joining two or more strings together.
This operation is commonly used to create full names, messages, labels, and formatted output.
firstName = "Aman"
lastName = "Sharma"
fullName = firstName + " " + lastName
Example: Join First Name and Last Name
/*
This program joins two strings.
*/
ENTRY POINT
DECLARE firstName AS TEXT = "Aman"
DECLARE lastName AS TEXT = "Sharma"
DECLARE fullName AS TEXT = firstName + " " + lastName
DISPLAY fullName
END ENTRY POINT
Expected Output
Aman Sharma
5. Substring Operation
A substring is a smaller part taken from a larger string.
Substring operations are useful when we need to extract a specific portion of text.
text = "Programming"
substring(text, 0, 7) = "Program"
Example: Extract a Substring
/*
This program extracts part of a string.
*/
ENTRY POINT
DECLARE text AS TEXT = "Programming"
DECLARE part AS TEXT = substring(text, 0, 7)
DISPLAY part
END ENTRY POINT
Expected Output
Program
6. Search or Find Operation
The search operation checks whether a character, word, or substring exists inside a string.
It may return a position, a true/false result, or a not-found value depending on the language and function.
email = "student@example.com"
Search for "@"
Result: Found
Example: Search for a Character
/*
This program checks whether @ exists in an email.
*/
ENTRY POINT
DECLARE email AS TEXT = "student@example.com"
DECLARE isFound AS BOOLEAN = false
FOR index FROM 0 TO length(email) - 1
IF email[index] == '@' THEN
SET isFound = true
BREAK
END IF
END FOR
IF isFound == true THEN
DISPLAY "@ symbol found"
ELSE
DISPLAY "@ symbol not found"
END IF
END ENTRY POINT
Expected Output
@ symbol found
7. Replace Operation
The replace operation changes one part of a string into another part.
text = "I like Java"
replace "Java" with "Programming"
Result = "I like Programming"
Example: Replace Text
/*
This program replaces one word with another.
*/
ENTRY POINT
DECLARE sentence AS TEXT = "I like old version"
DECLARE updatedSentence AS TEXT = replace(sentence, "old", "new")
DISPLAY updatedSentence
END ENTRY POINT
Expected Output
I like new version
8. Trim Operation
The trim operation removes extra spaces from the beginning and end of a string.
It is commonly used before validating user input.
name = " Riya "
After trim:
"Riya"
Example: Trim User Input
/*
This program removes extra spaces from user input.
*/
ENTRY POINT
DECLARE username AS TEXT = " Aman "
DECLARE cleanUsername AS TEXT = trim(username)
DISPLAY cleanUsername
END ENTRY POINT
Expected Output
Aman
9. Case Conversion
Case conversion changes letters to uppercase or lowercase.
It is useful for formatting text and comparing user input.
text = "Hello"
uppercase(text) = "HELLO"
lowercase(text) = "hello"
Example: Convert Case
/*
This program converts text to uppercase and lowercase.
*/
ENTRY POINT
DECLARE text AS TEXT = "Programming"
DISPLAY uppercase(text)
DISPLAY lowercase(text)
END ENTRY POINT
Expected Output
PROGRAMMING
programming
10. String Comparison
String comparison checks whether two strings are the same or different.
text1 = "Hello"
text2 = "Hello"
text1 == text2 → true
String comparison is often case-sensitive.
"Hello" == "hello" → false
Example: Compare Strings
/*
This program compares two strings.
*/
ENTRY POINT
DECLARE password AS TEXT = "Secret123"
DECLARE enteredPassword AS TEXT = "Secret123"
IF password == enteredPassword THEN
DISPLAY "Password matched"
ELSE
DISPLAY "Password not matched"
END IF
END ENTRY POINT
Expected Output
Password matched
11. Case-insensitive Comparison
Sometimes we want to compare strings without caring about uppercase or lowercase letters.
In that case, we can convert both strings to lowercase or uppercase before comparison.
"Kolkata" and "kolkata"
After lowercase:
"kolkata" and "kolkata"
Result: same
Example: Compare Without Case Difference
/*
This program compares city names without case sensitivity.
*/
ENTRY POINT
DECLARE city1 AS TEXT = "Kolkata"
DECLARE city2 AS TEXT = "kolkata"
IF lowercase(city1) == lowercase(city2) THEN
DISPLAY "City names are same"
ELSE
DISPLAY "City names are different"
END IF
END ENTRY POINT
Expected Output
City names are same
12. Split Operation
The split operation breaks one string into multiple parts using a separator.
text = "Apple,Banana,Mango"
split by comma:
["Apple", "Banana", "Mango"]
Example: Split Comma-separated Text
/*
This program splits a comma-separated string.
*/
ENTRY POINT
DECLARE fruitsText AS TEXT = "Apple,Banana,Mango"
DECLARE fruits AS ARRAY = split(fruitsText, ",")
DISPLAY fruits
END ENTRY POINT
Expected Output
["Apple", "Banana", "Mango"]
13. Join Operation
The join operation combines multiple string values into one string using a separator.
items = ["Apple", "Banana", "Mango"]
join with comma:
"Apple,Banana,Mango"
Example: Join String Items
/*
This program joins multiple strings into one.
*/
ENTRY POINT
DECLARE words AS ARRAY = ["Programming", "Mastery", "Course"]
DECLARE title AS TEXT = join(words, " ")
DISPLAY title
END ENTRY POINT
Expected Output
Programming Mastery Course
14. Reverse Operation
The reverse operation displays or creates a string in opposite order.
text = "CODE"
reverse(text) = "EDOC"
Example: Reverse a String
/*
This program reverses a string manually.
*/
ENTRY POINT
DECLARE text AS TEXT = "CODE"
DECLARE reversedText AS TEXT = ""
FOR index FROM length(text) - 1 DOWN TO 0
SET reversedText = reversedText + text[index]
END FOR
DISPLAY reversedText
END ENTRY POINT
Expected Output
EDOC
15. Character Checking Operations
Character checking operations are used to test what kind of character is present in a string.
Common Character Checks
- Check whether a character is alphabetic.
- Check whether a character is numeric.
- Check whether a character is uppercase.
- Check whether a character is lowercase.
- Check whether a character is a space.
- Check whether a string contains only digits.
- Check whether a string contains only letters.
Example: Check Whether Text Contains Only Digits
/*
This program checks whether a string contains only digits.
*/
ENTRY POINT
DECLARE phone AS TEXT = "9876543210"
DECLARE onlyDigits AS BOOLEAN = true
FOR index FROM 0 TO length(phone) - 1
IF phone[index] IS NOT DIGIT THEN
SET onlyDigits = false
BREAK
END IF
END FOR
IF onlyDigits == true THEN
DISPLAY "Phone number contains only digits"
ELSE
DISPLAY "Phone number contains invalid characters"
END IF
END ENTRY POINT
Expected Output
Phone number contains only digits
Real-World Example: Clean and Validate Username
Let us combine multiple string operations in one example.
/*
This program cleans and validates a username.
*/
ENTRY POINT
DECLARE username AS TEXT = " RiyaSen "
SET username = trim(username)
IF length(username) < 3 THEN
DISPLAY "Username is too short"
ELSE
DISPLAY "Username accepted: " + username
END IF
END ENTRY POINT
Expected Output
Username accepted: RiyaSen
Real-World Example: Extract Email Domain
String operations are commonly used to process email addresses.
/*
This program extracts the domain from an email address.
*/
ENTRY POINT
DECLARE email AS TEXT = "student@example.com"
DECLARE atIndex AS INTEGER = -1
FOR index FROM 0 TO length(email) - 1
IF email[index] == '@' THEN
SET atIndex = index
BREAK
END IF
END FOR
IF atIndex != -1 THEN
DECLARE domain AS TEXT = substring(email, atIndex + 1, length(email))
DISPLAY "Domain: " + domain
ELSE
DISPLAY "Invalid email"
END IF
END ENTRY POINT
Expected Output
Domain: example.com
String Operation Categories
| Category | Operations | Purpose |
|---|---|---|
| Inspection | Length, search, comparison, character checking. | Understand or validate the string. |
| Extraction | Indexing, substring, split. | Get part of the string. |
| Transformation | Uppercase, lowercase, trim, replace, reverse. | Create a changed version of the string. |
| Construction | Concatenation, join, formatting. | Build a new string from values. |
Important Note About Immutability
In many programming languages, strings are immutable. This means string operations usually do not change the original string directly.
Instead, they return a new string.
text = "hello"
newText = uppercase(text)
text remains "hello"
newText becomes "HELLO"
Common Beginner Mistakes
Mistakes
- Forgetting that string indexes usually start from
0. - Accessing an index outside the string length.
- Forgetting that spaces are counted in string length.
- Comparing strings without handling uppercase and lowercase differences.
- Not trimming user input before validation.
- Thinking replace modifies the original string directly in immutable languages.
- Using concatenation without spaces between words.
- Using substring with wrong start and end positions.
- Splitting text with the wrong separator.
- Not checking whether a search result was found or not.
Better Habits
- Always check string length before indexing.
- Remember that the last index is usually
length - 1. - Use trim before validating input.
- Convert both strings to same case before case-insensitive comparison.
- Store the result of string operations in a variable.
- Use meaningful variable names such as
cleanName,domain, andmessage. - Test with empty strings and strings containing spaces.
- Use built-in string functions when available.
- Write expected output before applying string operations.
- Practice string operations with real-world data such as names, emails, and phone numbers.
Best Practices for String Operations
Recommended Practices
- Use strings for text-based data only.
- Trim user input before validation.
- Normalize case before comparing text when case should not matter.
- Use substring carefully with valid indexes.
- Use split when one string contains multiple values.
- Use join when multiple string values need to become one string.
- Use replace for simple text substitution.
- Use built-in functions instead of manually writing complex logic unnecessarily.
- Check for empty strings before processing.
- Avoid unnecessary repeated concatenation inside very large loops when the language provides a better string builder or join mechanism.
Prerequisites Before Learning Common String Operations
Students should already understand:
Required Knowledge
- Variables and constants.
- Data types.
- Input and output.
- Operators.
- Conditions.
- Loops and iteration.
- Arrays and indexing.
- What strings are.
- String indexing and length basics.
Trace Table Example: Count Spaces
Let us count spaces in the string:
text = "Hello World"
spaceCount = 0
FOR index FROM 0 TO length(text) - 1
IF text[index] == ' ' THEN
SET spaceCount = spaceCount + 1
END IF
END FOR
| Index | Character | Is Space? | spaceCount |
|---|---|---|---|
0 |
H |
No | 0 |
1 |
e |
No | 0 |
2 |
l |
No | 0 |
3 |
l |
No | 0 |
4 |
o |
No | 0 |
5 |
space |
Yes | 1 |
Final value of spaceCount is 1.
Practice Activity: Predict the Output
Predict the output of the following pseudocode.
text = " Hello Programming "
cleanText = trim(text)
upperText = uppercase(cleanText)
DISPLAY upperText
DISPLAY length(cleanText)
Your Answer
Output:
________________________
________________________
Sample Answer
HELLO PROGRAMMING
17
Mini Quiz
What is the length operation?
The length operation counts the total number of characters in a string.
What is concatenation?
Concatenation means joining two or more strings together.
What does trim do?
Trim removes extra spaces from the beginning and end of a string.
What does split do?
Split breaks a string into multiple parts using a separator.
Why do we convert strings to lowercase before comparison?
We convert strings to lowercase when we want comparison to ignore uppercase and lowercase differences.
Interview Questions on Common String Operations
Name some common string operations.
Common string operations include length, indexing, concatenation, substring, search, replace, trim, split, join, case conversion, and comparison.
What is the difference between split and join?
Split breaks one string into multiple parts, while join combines multiple string parts into one string.
Why is trim useful?
Trim is useful because user input may contain extra spaces, and removing them helps validation and comparison.
What is string replacement?
String replacement means changing one character, word, or substring into another value.
What is the importance of string operations?
String operations are important because they help programs clean, validate, search, format, and process text data.
Quick Summary
| Operation | Meaning |
|---|---|
| Length | Counts characters. |
| Indexing | Accesses character by position. |
| Concatenation | Joins strings. |
| Substring | Extracts part of a string. |
| Search | Finds character or word. |
| Replace | Changes old text to new text. |
| Trim | Removes extra beginning and ending spaces. |
| Split | Breaks string into parts. |
| Join | Combines parts into a string. |
| Case Conversion | Changes uppercase or lowercase. |
Final Takeaway
Common string operations are essential tools for working with text data in programming. They help us measure text, access characters, join strings, extract substrings, search values, replace text, clean spaces, split data, join parts, compare strings, and convert case. In the Programming Mastery Course, students should practice these operations with real-world examples such as usernames, emails, phone numbers, messages, and form validation.