← Back to Lab HomeLab Exercise – 08
Experiment 8 – String Operations
Aim
To implement basic string manipulation operations including finding string length, copying strings, concatenating strings, and comparing strings without using built-in string functions in C programming. This experiment helps students understand how strings work internally as character arrays and how to manipulate them using loops and pointer arithmetic.
Through this experiment, students will learn to work with null-terminated strings, understand the importance of the null character ('\0'), and implement fundamental string operations that form the basis of more complex text processing tasks.
Learning Outcomes
After completing this experiment, students will be able to:
- Understand how strings are stored as character arrays with null termination
- Implement string length calculation by counting characters until null terminator
- Implement string copy operation character by character
- Implement string concatenation by appending one string to another
- Implement string comparison by comparing characters lexicographically
- Work with null-terminated strings and understand their importance
- Use loops and pointer arithmetic for string manipulation
- Handle edge cases in string operations (empty strings, null pointers)
Algorithm
The algorithms for each string operation are as follows:
String Length Algorithm:
- Initialize counter
len = 0 - Loop through string until null character is found
- Increment counter for each character
- Return counter value
String Copy Algorithm:
- Loop through source string until null character
- Copy each character from source to destination
- Add null character at the end of destination
String Concatenate Algorithm:
- Find the end of first string (position of null character)
- Starting from that position, copy characters from second string
- Add null character at the end
String Compare Algorithm:
- Compare characters one by one from both strings
- If characters differ, return their difference (str1[i] - str2[i])
- If one string ends, return difference in lengths
- If both are identical, return 0
Procedure
- Include
stdio.hand optionallystring.h - Declare character arrays (strings) for operations
- For String Length:
- Loop until null character ('\0') is found
- Count characters
- For String Copy:
- Copy each character from source to destination
- Add null character at the end
- For String Concatenate:
- Find end of first string
- Append characters from second string
- Add null character
- For String Compare:
- Compare characters one by one
- Return 0 if equal, positive/negative if different
- Display results of all operations
Flowchart
String Length:
START
├─→ Declare: str[], len = 0, i = 0
├─→ Read str
├─→ WHILE (str[i] != '