Trim leading and trailing spaces Dry Run in C

Trim leading and trailing spaces is an interactive C dry run visualizer from the String Functions programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Trim leading and trailing spaces Program Code

#include <stdio.h>
#include <string.h>

char* trim(char str[]) {
    int start = 0;
    int end = strlen(str) - 1;
    
    // Find first non-space character
    while(str[start] == ' ') {
        start++;
    }
    
    // Find last non-space character
    while(end >= start && str[end] == ' ') {
        end--;
    }
    
    // Shift string to beginning
    int i = 0;
    for(int j = start; j <= end; j++) {
        str[i++] = str[j];
    }
    str[i] = '\0';
    
    return str;
}

int main() {
    char str[] = "   Hello World   ";
    
    printf("Original: '%s'\n", str);
    printf("Length: %lu\n", strlen(str));
    
    trim(str);
    
    printf("Trimmed: '%s'\n", str);
    printf("Length: %lu\n", strlen(str));
    
    return 0;
}

View the complete String Functions programs page.

Program Console Trim leading and trailing spaces Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.