String operations are actions you perform on strings: finding length, comparing, concatenating (joining), copying, and checking properties like palindromes. Most operations require walking through the string character by character.
Think of string operations like working with a necklace: Length = count pearls until you hit the clasp. Compare = check if two necklaces have the same pearls in the same order. Concatenate = join two necklaces together.
Ready
"HI\\0"
The Rule: Count characters BEFORE the null terminator.
1// Length2int len = strlen(str); // O(n) - counts until \034// Compare5if (strcmp(str1, str2) == 0) { // O(n) - compares character by character6// Strings are equal7}89// Concatenate10strcat(dest, src); // O(n) - finds end of dest, then copies src1112// Copy13strcpy(dest, src); // O(n) - copies each character including \01415// All operations are O(n) because strings don't store length!
Let's explore each operation step by step.
1. Length (strlen)
The computer doesn't store the length separately. It has to COUNT characters until it finds \0:
2. Compare (strcmp)
Check if two strings are identical:
3. Concatenate (strcat)
Join two strings together:
4. Copy (strcpy)
Copy one string to another:
5. Palindrome Check
Check if string reads same forwards and backwards:
The Common Pattern
Notice something? Almost all string operations are O(n). Why? Because strings don't store their length — you must walk through them to find \0 or process each character.
These are the building blocks of string manipulation. Every program that handles text uses these operations. Understanding their time complexity helps you write efficient code.
"What is the time complexity of finding the length of a string?"
O(n), where n is the length of the string. The computer must count characters until it finds the null terminator, checking each character once.