REIMPLEMENT BUILT IN STRING FUNCTIONS
STRING :
A string is a sequence of characters, typically used to represent text. In most
programming languages, including Python, C, Java, and many others, a string is
a data type that allows you to store and manipulate a series of characters,
such as letters, numbers, symbols, and whitespace.
You can create a string by enclosing characters in either single quotes (') or
double quotes (").
For example:
string1 = "This is a string."
string2 = 'This is also a string.'
Here are the re-implemented string functions with examples :
1: ‘custom_len()’ - Re-implementation of len() function
def custom_len(s):
count = 0
for char in s:
count += 1
return count
# Example:
text = "Hello, World!"
length = custom_len(text)
print("Custom Length:", length) # Output: 13
2 : ‘custom_upper()’ - Re-implementation of ‘upper()’ function:
def custom_upper(s):
result = ""
for char in s:
if 'a' <= char <= 'z':
result += chr(ord(char) - 32)
else:
result += char
return result
# Example:
text = "Hello, World!"
uppercase_text = custom_upper(text)
print("Custom Upper:", uppercase_text) # Output: "HELLO, WORLD!"
3 : ‘custom_lower()’ - Re-implementation of ‘lower()’ function:
def custom_lower(s):
result = ""
for char in s:
if 'A' <= char <= 'Z':
result += chr(ord(char) + 32)
else:
result += char
return result
# Example:
text = "Hello, World!"
lowercase_text = custom_lower(text)
print("Custom Lower:", lowercase_text) # Output: "hello, world!"
4 : ‘custom_strip()’ - Re-implementation of ‘strip()’ function:
def custom_strip(s):
start, end = 0, len(s) - 1
while start <= end and s[start].isspace():
start += 1
while end >= start and s[end].isspace():
end -= 1
return s[start:end + 1]
# Example:
text = " Hello, World! "
stripped_text = custom_strip(text)
print("Custom Strip:", stripped_text) # Output: "Hello, World!"
IDENTIFY COMMON SYNTACTICAL ERRORS
WHEN WORKING WITH ARRAYS AND STRINGS
When working with arrays and strings in programming, there are several
common syntactical errors that developers often make. These errors can lead to
runtime issues, logical bugs, and unexpected behavior. Here are some of the
most common syntactical errors to watch out for when working with arrays
and string
1 : Off-by-One Errors:
These occur when you access an array or string element with an incorrect
index.
• Error: Accessing an element with an incorrect index, often going one
index beyond the end.
Example :
my_array = [1, 2, 3]
# Accessing an element out of bounds
element = my_array[3] # IndexError
2 : String Indexing Errors:
In many programming languages, strings are zero-indexed, meaning the first
character is at index 0. Not accounting for this can lead to incorrect character
access.
• Error: Not accounting for zero-based indexing when accessing string
characters.
Example:
my_string = "Hello"
# Accessing the first character incorrectly
first_char = my_string[1] # Retrieves 'e' instead of 'H'
3 : Forgetting to Escape Special Characters:
When working with strings that contain special characters (e.g., quotation
marks or backslashes), you need to escape them to avoid syntax errors.
• Error: Not escaping special characters within strings, leading to syntax
errors.
Example:
my_string = "This is a "quoted" string." # SyntaxError
4 : String Concatenation Errors:
Using incorrect syntax for string concatenation can lead to unexpected results.
The correct operator or method for concatenating strings may vary between
programming languages.
• Error: Using incorrect syntax for string concatenation.
Example:
# Concatenation error (use + operator)
result = "Hello" . "World" # SyntaxError
5 : Array Initialization Errors:
Incorrectly initializing arrays can lead to unexpected behavior or errors. Ensure
that the array is correctly defined with the appropriate elements.
• Error: Incorrectly initializing arrays, such as using a trailing comma.
Example:
# Initializing an array with incorrect syntax
my_array = [1, 2, 3,] # SyntaxError
6 : Array and String Bounds Errors:
Accessing or manipulating elements beyond the bounds of an array or string
can lead to memory corruption or segmentation faults.
• Error: Accessing or modifying elements beyond the bounds of an array
or string.
Example:
char my_string[] = "Hello";
// Trying to modify a character beyond the array's size
my_string[5] = '!'; // Out of bounds
7 : String Format Errors:
When using string formatting functions or methods, ensure that the format
specifier matches the argument type. Mismatched types can result in
unexpected output or runtime errors.
• Error: Mismatch between format specifiers and argument types when
formatting strings.
Example:
# Format specifier and argument type mismatch
formatted_string = "Value: %s" % 42 # Should be "Value: %d" for an integer
8 : Array and String Equality Errors:
When comparing arrays or strings for equality, use the appropriate
equality operators or methods based on the programming language. Using
== or != may not work as expected.
• Error: Using incorrect operators for comparing arrays or strings.
Example:
arr1 = [1, 2, 3]
arr2 = [1, 2, 3]
if arr1 is arr2:
# Incorrect array comparison (use ==)
str1 = "Hello"
str2 = "World"
if str1 != str2:
# Incorrect string comparison (use ==)
9 : Case Sensitivity:
Some programming languages are case-sensitive, meaning that "myString"
and "mystring" are considered different variables or identifiers. Ensure
consistent casing.
• Error: Forgetting that some programming languages are case-sensitive,
resulting in different variables or identifiers.
Example:
char myString[] = "Hello";
// Attempting to use a different case for the variable name
char mystring[] = "World"; // Results in two separate variables
10 : Array and String Initialization:
Make sure to initialize arrays and strings properly before using them.
Uninitialized variables can lead to unpredictable behavior.
• Error: Not initializing arrays and strings properly before using them,
leading to unpredictable behavior.
Example:
char myString[10]; // Uninitialized string
EXPERIMENT NO 8
IDENTIFY THE USE CASES AND SOLVE THEM
USING ARRAYS
ARRAYS:
Arrays are fundamental data structures in programming that allow you to
store and manipulate collections of data. Here are some common use cases
for arrays, along with examples of how to solve them using arrays in
various programming languages.
1: Storing a List of Items:
Use an array to store and manage a list of items.
Example:
const numbers = [1, 2, 3, 4, 5];
2: Accessing Elements by Index:
Retrieve elements from the array by their index.
Example:
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[1]); // Output: 'banana'
3: Modifying Elements:
Change the value of an element at a specific index.
Example:
const colors = ['red', 'green', 'blue'];
colors[0] = 'pink';
console.log(colors); // Output: ['pink', 'green', 'blue']
4: Adding Elements:
Add elements to the end of an array using ‘push’.
Example:
const animals = ['cat', 'dog'];
animals.push('elephant');
console.log(animals); // Output: ['cat', 'dog', 'elephant']
5: Removing Elements:
Remove elements from the end of an array using ‘pop’.
Example:
const fruits = ['apple', 'banana', 'cherry'];
fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
6: Searching for an Element:
Use the ‘indexOf’ method to find the index of a specific element.
Example:
const languages = ['Java', 'Python', 'JavaScript'];
const index = languages.indexOf('Python');
console.log(index); // Output: 1
7: Iterating through an Array:
Use loops to iterate through all elements in an array.
Example:
const days = ['Monday', 'Tuesday', 'Wednesday'];
for (const day of days) {
console.log(day);
}
// Output:
// 'Monday'
// 'Tuesday'
// 'Wednesday'
8: Filtering Elements:
Create a new array by filtering elements that meet a certain condition.
Example:
const numbers = [10, 20, 30, 40, 50];
const filteredNumbers = numbers.filter(num => num > 25);
console.log(filteredNumbers); // Output: [30, 40, 50]
9: Sorting an Array:
Sort the elements in an array in ascending order.
Example:
const fruits = ['banana', 'cherry', 'apple'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry']