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:

  1. Initialize counter len = 0
  2. Loop through string until null character is found
  3. Increment counter for each character
  4. Return counter value

String Copy Algorithm:

  1. Loop through source string until null character
  2. Copy each character from source to destination
  3. Add null character at the end of destination

String Concatenate Algorithm:

  1. Find the end of first string (position of null character)
  2. Starting from that position, copy characters from second string
  3. Add null character at the end

String Compare Algorithm:

  1. Compare characters one by one from both strings
  2. If characters differ, return their difference (str1[i] - str2[i])
  3. If one string ends, return difference in lengths
  4. If both are identical, return 0

Procedure

  1. Include stdio.h and optionally string.h
  2. Declare character arrays (strings) for operations
  3. For String Length:
    • Loop until null character ('\0') is found
    • Count characters
  4. For String Copy:
    • Copy each character from source to destination
    • Add null character at the end
  5. For String Concatenate:
    • Find end of first string
    • Append characters from second string
    • Add null character
  6. For String Compare:
    • Compare characters one by one
    • Return 0 if equal, positive/negative if different
  7. Display results of all operations

Flowchart

String Length:
  START
    ├─→ Declare: str[], len = 0, i = 0
    ├─→ Read str
    ├─→ WHILE (str[i] != '')
    │   │
    │   ├─→ len++
    │   └─→ i++
    │
    └─→ Display len

String Copy:
  START
    ├─→ Declare: src[], dest[], i = 0
    ├─→ Read src
    ├─→ WHILE (src[i] != '')
    │   │
    │   ├─→ dest[i] = src[i]
    │   └─→ i++
    │
    ├─→ dest[i] = ''
    └─→ Display dest

String Concatenate:
  START
    ├─→ Declare: str1[], str2[], i, j = 0
    ├─→ Find length of str1 → i
    ├─→ WHILE (str2[j] != '')
    │   │
    │   ├─→ str1[i] = str2[j]
    │   ├─→ i++
    │   └─→ j++
    │
    ├─→ str1[i] = ''
    └─→ Display str1

Program Code

#include <stdio.h>

// Function to calculate string length
int stringLength(char str[]) {
    int len = 0;
    while (str[len] != '\0') {
        len++;
    }
    return len;
}

// Function to copy string
void stringCopy(char dest[], char src[]) {
    int i = 0;
    while (src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';
}

// Function to concatenate strings
void stringConcat(char str1[], char str2[]) {
    int i = 0, j = 0;
    
    // Find end of str1
    while (str1[i] != '\0') {
        i++;
    }
    
    // Append str2 to str1
    while (str2[j] != '\0') {
        str1[i] = str2[j];
        i++;
        j++;
    }
    str1[i] = '\0';
}

// Function to compare strings
int stringCompare(char str1[], char str2[]) {
    int i = 0;
    while (str1[i] != '\0' && str2[i] != '\0') {
        if (str1[i] != str2[i]) {
            return str1[i] - str2[i];
        }
        i++;
    }
    return str1[i] - str2[i];
}

int main() {
    char str1[100], str2[100], str3[100];
    int len, result;
    
    // String Length
    printf("Enter a string: ");
    scanf("%s", str1);
    len = stringLength(str1);
    printf("Length of '%s' is: %d\n\n", str1, len);
    
    // String Copy
    printf("Enter source string: ");
    scanf("%s", str1);
    stringCopy(str2, str1);
    printf("Copied string: %s\n\n", str2);
    
    // String Concatenate
    printf("Enter first string: ");
    scanf("%s", str1);
    printf("Enter second string: ");
    scanf("%s", str2);
    stringCopy(str3, str1);  // Copy str1 to preserve original
    stringConcat(str3, str2);
    printf("Concatenated string: %s\n\n", str3);
    
    // String Compare
    printf("Enter first string: ");
    scanf("%s", str1);
    printf("Enter second string: ");
    scanf("%s", str2);
    result = stringCompare(str1, str2);
    if (result == 0) {
        printf("Strings are equal.\n");
    } else if (result > 0) {
        printf("'%s' is greater than '%s'\n", str1, str2);
    } else {
        printf("'%s' is less than '%s'\n", str1, str2);
    }
    
    return 0;
}

Sample Input and Output

Sample 1: String Length

Input:

Enter a string: Programming

Output:

Length of 'Programming' is: 11

Sample 2: String Copy

Input:

Enter source string: Hello

Output:

Copied string: Hello

Sample 3: String Concatenate

Input:

Enter first string: Hello
Enter second string: World

Output:

Concatenated string: HelloWorld

Sample 4: String Compare

Input:

Enter first string: Apple
Enter second string: Banana

Output:

'Apple' is less than 'Banana'

Use Case / Real-world Relevance

String operations are fundamental in text processing and are used extensively:

  • Text Processing: Word processors, text editors, and document management systems
  • Search Engines: String matching, searching, and indexing operations
  • Data Validation: Checking input formats, email validation, password strength
  • Parsing: Breaking down text into tokens, parsing configuration files, JSON/XML processing
  • Database Operations: SQL queries, string matching in WHERE clauses
  • Web Development: URL processing, form data handling, template engines
  • Compiler Design: Lexical analysis, tokenization, parsing source code
  • Natural Language Processing: Text analysis, sentiment analysis, language translation

Understanding how strings work at a low level (as character arrays) is crucial for efficient text processing and is fundamental to many programming tasks. These operations form the foundation for more advanced string manipulation, parsing, and text processing algorithms used in compilers, interpreters, and text editors.

Viva Questions

Q1: Why is the null character ('\0') important in C strings?

The null character marks the end of a string. Without it, functions wouldn't know where the string ends, leading to reading beyond allocated memory (buffer overflow). All string functions rely on finding '\0' to determine string length and boundaries. It's automatically added by string literals and must be manually added when building strings character by character.

Q2: What happens if we forget to add '\0' at the end of a string?

Without the null terminator, string functions will continue reading memory beyond the intended string until they find a null byte (which may be far away) or cause a segmentation fault. This leads to undefined behavior, potential crashes, and security vulnerabilities like buffer overflows. Always ensure strings are properly null-terminated.

Q3: How does string comparison work? What values does it return?

String comparison compares characters lexicographically (dictionary order). Returns 0 if strings are equal, positive value if first string is greater (comes later alphabetically), negative value if first string is less. Comparison stops at first differing character or when one string ends. Example: "apple" < "banana" (negative), "zebra" > "apple" (positive).

Q4: What is the difference between strcpy and strncpy?

strcpy copies entire string until null character. strncpycopies specified number of characters, padding with nulls if source is shorter. strncpy is safer for fixed-size buffers as it prevents overflow, but doesn't automatically null-terminate if source length equals or exceeds the limit.

Q5: Why do we need to check if destination has enough space before concatenation?

Concatenation appends characters to the end of the first string. If the destination array doesn't have enough space, writing beyond its bounds causes buffer overflow - overwriting adjacent memory, potentially corrupting data or causing crashes. Always ensure destination array is large enough to hold both strings plus the null terminator.

Q6: Can we use array indexing instead of pointer arithmetic for string operations?

Yes, both are equivalent. str[i] and *(str + i)access the same element. Array indexing is more readable, while pointer arithmetic can be more efficient in some cases. Choose based on readability and coding style preferences. The compiler often optimizes both to the same code.

Q7: What is the time complexity of these string operations?

All operations are O(n) where n is the string length: length requires scanning until null, copy requires copying n characters, concatenate requires finding end of first (O(m)) then copying second (O(n)), compare requires comparing up to n characters. These are optimal as we must examine each character at least once.

Q8: How would you reverse a string using these basic operations?

Use two pointers (start and end), swap characters, move pointers toward center until they meet. Or copy string to temporary, then copy back in reverse order. The two-pointer approach is more efficient (O(n) time, O(1) extra space) compared to using a temporary array.

Related Links

🔹 Author: Dr. J. Siva Ramakrishna

🔹 Institution: Narayana Engineering College, Gudur

🔹 Last Updated: 9 January 2026